WSL/SLF GitLab Repository

NetCDFIO.cc 52.6 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 "NetCDFIO.h"
19
#include <meteoio/Timer.h>
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

using namespace std;

namespace mio {
/**
 * @page netcdf NetCDF
 * @section netcdf_format Format
 * *Put here the informations about the standard format that is implemented*
 *
 * @section netcdf_units Units
 *
 *
 * @section netcdf_keywords Keywords
 * This plugin uses the following keywords:
 * - COORDSYS: coordinate system (see Coords); [Input] and [Output] section
 * - COORDPARAM: extra coordinates parameters (see Coords); [Input] and [Output] section
36
37
 * - DEMFILE: The filename of the file containing the DEM; [Input] section 
 * - DEMVAR: The variable name of the DEM within the DEMFILE; [Input] section 
38
 * - METEOFILE: the NetCDF file which shall be used for the meteo parameter input/output; [Input] and [Output] section
39
 * - GRID2DFILE: the NetCDF file which shall be used for gridded input/output; [Input] and [Output] section
40
41
 */

42
const double NetCDFIO::plugin_nodata = -9999999.; //CNRM-GAME nodata value
43
44
45
46
47
const std::string NetCDFIO::lat_str = "lat";
const std::string NetCDFIO::lon_str = "lon";
const std::string NetCDFIO::z_str = "z";
const std::string NetCDFIO::ta_str = "temperature";
const std::string NetCDFIO::rh_str = "humidity";
48

49
50
51
52
53
const std::string NetCDFIO::cf_time = "time";
const std::string NetCDFIO::cf_units = "units";
const std::string NetCDFIO::cf_days = "days since ";
const std::string NetCDFIO::cf_seconds = "seconds since ";

54
55
56
const std::string NetCDFIO::cnrm_points = "Number_of_points";
const std::string NetCDFIO::cnrm_latitude = "LAT";
const std::string NetCDFIO::cnrm_longitude = "LON";
57
58
59
const std::string NetCDFIO::cnrm_altitude = "ZS";
const std::string NetCDFIO::cnrm_aspect = "aspect";
const std::string NetCDFIO::cnrm_slope = "slope";
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const std::string NetCDFIO::cnrm_ta = "Tair";
const std::string NetCDFIO::cnrm_rh = "HUMREL";
const std::string NetCDFIO::cnrm_vw = "Wind";
const std::string NetCDFIO::cnrm_dw = "Wind_DIR";
const std::string NetCDFIO::cnrm_qair = "Qair";
const std::string NetCDFIO::cnrm_co2air = "CO2air";
const std::string NetCDFIO::cnrm_theorsw = "theorSW";
const std::string NetCDFIO::cnrm_neb = "NEB";
const std::string NetCDFIO::cnrm_hnw = "Rainf";
const std::string NetCDFIO::cnrm_snowf = "Snowf";
const std::string NetCDFIO::cnrm_swr_direct = "DIR_SWdown";
const std::string NetCDFIO::cnrm_swr_diffuse = "SCA_SWdown";
const std::string NetCDFIO::cnrm_p = "PSurf";
const std::string NetCDFIO::cnrm_ilwr = "LWdown";
Thomas Egger's avatar
Thomas Egger committed
74
const std::string NetCDFIO::cnrm_timestep = "FRC_TIME_STP";
75

76
std::map<std::string, size_t> NetCDFIO::paramname;
77
std::map<std::string, std::string> NetCDFIO::map_name;
78
79
80
81
82
const bool NetCDFIO::__init = NetCDFIO::initStaticData();

bool NetCDFIO::initStaticData()
{
	//Associate unsigned int value and a string representation of a meteo parameter
83
84
85
86
87
88
89
90
91
92
93
94
95
96
	paramname[cnrm_ta] = MeteoData::TA;
	//paramname[cnrm_qair] = IOUtils::npos; // not a standard MeteoIO parameter
	//paramname[cnrm_co2air] = IOUtils::npos; // not a standard MeteoIO parameter
	//paramname[cnrm_neb] = IOUtils::npos; // not a standard MeteoIO parameter
	//paramname[cnrm_theorsw] = IOUtils::npos; // not a standard MeteoIO parameter
	paramname[cnrm_rh] = MeteoData::RH;
	paramname[cnrm_vw] = MeteoData::VW;
	paramname[cnrm_dw] = MeteoData::DW;
	paramname[cnrm_hnw] = IOUtils::npos;
	paramname[cnrm_snowf] = IOUtils::npos;
	paramname[cnrm_swr_direct] = IOUtils::npos;
	paramname[cnrm_swr_diffuse] = IOUtils::npos;
	paramname[cnrm_p] = MeteoData::P;
	paramname[cnrm_ilwr] = MeteoData::ILWR;
97

98
99
100
101
102
103
	map_name["TA"] = cnrm_ta;
	map_name["RH"] = cnrm_rh;
	map_name["ILWR"] = cnrm_ilwr;
	map_name["P"] = cnrm_p;
	map_name["VW"] = cnrm_vw;
	map_name["DW"] = cnrm_dw;
Thomas Egger's avatar
Thomas Egger committed
104
	map_name["ISWR"] = cnrm_swr_direct;
105

106
107
108
109
110
	return true;
}

NetCDFIO::NetCDFIO(const std::string& configfile) : cfg(configfile), coordin(""), coordinparam(""), coordout(""), coordoutparam(""),
                                                    in_dflt_TZ(0.), out_dflt_TZ(0.), vecMetaData()
111
112
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
113
	parseInputOutputSection();
114
115
}

116
117
NetCDFIO::NetCDFIO(const Config& cfgreader) : cfg(cfgreader), coordin(""), coordinparam(""), coordout(""), coordoutparam(""),
                                              in_dflt_TZ(0.), out_dflt_TZ(0.), vecMetaData()
118
119
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
120
	parseInputOutputSection();
121
122
123
124
125
126
127
}

NetCDFIO::~NetCDFIO() throw()
{

}

128
129
130
131
132
133
134
135
void NetCDFIO::parseInputOutputSection()
{
	//default timezones
	in_dflt_TZ = out_dflt_TZ = IOUtils::nodata;
	cfg.getValue("TIME_ZONE", "Input", in_dflt_TZ, IOUtils::nothrow);
	cfg.getValue("TIME_ZONE", "Output", out_dflt_TZ, IOUtils::nothrow);
}

136
void NetCDFIO::read2DGrid(Grid2DObject& grid_out, const std::string& arguments)
137
{
138
139
140
141
142
143
144
145
	vector<string> vec_argument;
	IOUtils::readLineToVec(arguments, vec_argument, ':');

	if (vec_argument.size() == 2) {
		read2DGrid_internal(grid_out, vec_argument[0], vec_argument[1]);
	} else {
		throw InvalidArgumentException("The format for the arguments to NetCDFIO::read2DGrid is filename:varname", AT);
	}
146
147
}

148
void NetCDFIO::read2DGrid(Grid2DObject& grid_out, const MeteoGrids::Parameters& parameter, const Date& date)
149
{
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
	string filename("");
	cfg.getValue("GRID2DFILE", "Input", filename);

	string varname = get_varname(parameter);

	int ncid, varid;
	vector<int> dimid, dim_varid; 
	vector<string> dimname;
	vector<size_t> dimlen;

	open_file(filename, NC_NOWRITE, ncid);
	get_variable(ncid, varname, varid);
	get_dimension(ncid, varname, varid, dimid, dim_varid, dimname, dimlen);

	if (dimid.size()!=3 || dimlen[0]<1 || dimlen[1]<2 || dimlen[2]<2)
		throw IOException("Variable '" + varname + "' may only have three dimensions, all have to have length >1", AT);

	cout << "Dimensions: " << dimlen[1] << " x " << dimlen[2] << " (" << dimlen[0]  << "timesteps)" << endl;

169
	size_t pos = find_record(ncid, NetCDFIO::cf_time, dimid[0], date.getModifiedJulianDate());
170
171
	if (pos == IOUtils::npos) 
		throw IOException("No record for date " + date.toString(Date::ISO), AT);
172

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
	double *lat = new double[dimlen[1]];
	double *lon = new double[dimlen[2]];
	double *grid = new double[dimlen[1]*dimlen[2]];

	read_data(ncid, varname, varid, pos, dimlen[1], dimlen[2], grid);
	read_data(ncid, dimname[1], dim_varid[1], lat);
	read_data(ncid, dimname[2], dim_varid[2], lon);

	copy_grid(dimlen[1], dimlen[2], lat, lon, grid, grid_out);

	close_file(filename, ncid);

	delete[] lat;
	delete[] lon;
	delete[] grid;

	cout << "Grid2DObject: " << grid_out.ncols << " x " << grid_out.nrows << "  Cellsize: " << grid_out.cellsize << endl;
190
191
}

192
void NetCDFIO::read2DGrid_internal(Grid2DObject& grid_out, const std::string& filename, const std::string& varname)
193
{
194
195
196
197
198
199
200
201
202
	int ncid, varid;
	vector<int> dimid, dim_varid; 
	vector<string> dimname;
	vector<size_t> dimlen;

	open_file(filename, NC_NOWRITE, ncid);
	get_variable(ncid, varname, varid);
	get_dimension(ncid, varname, varid, dimid, dim_varid, dimname, dimlen);

203
204
	if (dimid.size()!=2 || dimlen[0]<2 || dimlen[1]<2)
		throw IOException("Variable '" + varname + "' may only have two dimensions and both have to have length >1", AT);
205
206
207
208
209
210
211
212
213
214
215

	cout << "Dimensions: " << dimlen[0] << " x " << dimlen[1] << endl;

	double *lat = new double[dimlen[0]];
	double *lon = new double[dimlen[1]];
	double *grid = new double[dimlen[0]*dimlen[1]];
	
	read_data(ncid, varname, varid, grid);
	read_data(ncid, dimname[0], dim_varid[0], lat);
	read_data(ncid, dimname[1], dim_varid[1], lon);

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
	copy_grid(dimlen[0], dimlen[1], lat, lon, grid, grid_out);

	close_file(filename, ncid);

	delete[] lat;
	delete[] lon;
	delete[] grid;

	cout << "Grid2DObject: " << grid_out.ncols << " x " << grid_out.nrows << "  Cellsize: " << grid_out.cellsize << endl;
}

void NetCDFIO::copy_grid(const size_t& latlen, const size_t& lonlen, double*& lat, double*& lon, double*& grid, Grid2DObject& grid_out)
{
	
	cout << "Lat: " << latlen << endl;
	cout << "Lon: " << lonlen << endl;
232
	cout << "Starting to copy to Grid2DObject...";
233

234
235
	Coords location(coordin, coordinparam);
	location.setLatLon(lat[0], lon[0], grid[0]);
236
237

	double resampling_factor = IOUtils::nodata;
238
	double cellsize = calculate_cellsize(latlen, lonlen, lat, lon, resampling_factor);
239
240
241

	cout << "Detected a cellsize of: " << cellsize << endl;

242
	grid_out.set(lonlen, latlen, cellsize, location);
243

244
245
246
	for (size_t kk=0; kk < latlen; kk++) {
		for (size_t ll=0; ll < lonlen; ll++) {
			grid_out(ll, kk) = IOUtils::standardizeNodata(grid[kk*lonlen + ll], plugin_nodata);
247
248
249
		}
	}

250
251
252
253
254
255
	if (resampling_factor != IOUtils::nodata) {
		/*
		cout << "(0,0): " << grid_out.grid2D(0,0) << endl;
		cout << "(0,1): " << grid_out.grid2D(0,1) << endl;
		cout << "(1,0): " << grid_out.grid2D(1,0) << endl;
		*/
256
		cout << "Resampling required... " << endl;
257
258
259
260
261
262
263
264
265
266
		grid_out.grid2D = ResamplingAlgorithms2D::BilinearResampling(grid_out.grid2D, resampling_factor, 1.0);
		/*
		cout << "(0,0): " << grid_out.grid2D(0,0) << endl;
		cout << "(0,1): " << grid_out.grid2D(0,1) << endl;
		cout << "(1,0): " << grid_out.grid2D(1,0) << endl;
		*/
		grid_out.ncols = grid_out.grid2D.getNx();
		grid_out.nrows = grid_out.grid2D.getNy();
	}
	//cout << "Finished" << endl;
267
268
}

269
270
double NetCDFIO::calculate_cellsize(const size_t& latlen, const size_t& lonlen, 
                                    double* const& lat, double* const& lon, double& factor)
271
{
272
273
274
	cout << setprecision(9) << setw(20) << endl;
	cout << "Lat[0]: " << lat[0] << "   Lat[end]: " << lat[latlen-1] << endl;
	cout << "Lon[0]: " << lon[0] << "   Lon[end]: " << lon[lonlen-1] << endl;
275

276
277
278
279
280
281
282
283
284
285
286
	double alpha = 0.;
	double distanceX = Coords::cosineDistance(lat[0], lon[0], lat[0], lon[lonlen-1], alpha);
	//cout << "AlphaX: " << alpha << endl;
	double distanceY = Coords::cosineDistance(lat[0], lon[0], lat[latlen-1], lon[0], alpha);
	//cout << "AlphaY: " << alpha << endl;
	double checkX = Coords::cosineDistance(lat[0], lon[0], lat[0], lon[1], alpha);
	double checkY = Coords::cosineDistance(lat[0], lon[0], lat[1], lon[0], alpha);

	bool equal = IOUtils::checkEpsilonEquality(distanceX, distanceY, 1.0);
	bool check1 = IOUtils::checkEpsilonEquality(checkX, distanceX, 1.0);
	bool check2 = IOUtils::checkEpsilonEquality(checkY, distanceY, 1.0);
287

288
289
290
291
292
293
294
295
296
297
298
299
300
	cout << endl;

	cout << "Latlen: " << Coords::lat_degree_lenght(lat[latlen/2]) << endl;
	cout << "Lonlen: " << Coords::lon_degree_lenght(lat[latlen/2]) << endl;

	cout << "DistanceX: " <<  distanceX << endl;;
	cout << "DistanceY: " <<  distanceY << endl;;

	cout << "CellsizeX: " << (distanceX/lonlen) << endl;
	cout << "CellsizeY: " << (distanceY/latlen) << endl;

	cout << "CheckX: " << checkX << endl;
	cout << "CheckY: " << checkY << endl;
301

302
303
304
305
306
307
308
309
310

	//HACK: Check which cellsize is larger, use that one
	if (equal && check1 && check2) {
		return distanceY/latlen;
	} else {
		factor =  (distanceX/lonlen) / (distanceY/latlen);
		//cout << "Factor: " << factor << endl;
		return distanceY/latlen;
	}
311
312
}

313
314
315
316
317
318
void NetCDFIO::readDEM(DEMObject& dem_out)
{
	string filename(""), varname("");
	
	cfg.getValue("DEMFILE", "Input", filename);
	cfg.getValue("DEMVAR", "Input", varname);
319

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
	read2DGrid_internal(dem_out, filename, varname);
}

void NetCDFIO::readLanduse(Grid2DObject& /*landuse_out*/)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void NetCDFIO::readAssimilationData(const Date& /*date_in*/, Grid2DObject& /*da_out*/)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void NetCDFIO::readStationData(const Date&, std::vector<StationData>& vecStation)
{
	if (!vecMetaData.empty()) {
		vecStation = vecMetaData;
		return;
	}

	string filename("");
	cfg.getValue("METEOFILE", "Input", filename);

	int ncid;

	open_file(filename, NC_NOWRITE, ncid);
	readMetaData(ncid, vecMetaData);
	close_file(filename, ncid);

	vecStation = vecMetaData;
}

void NetCDFIO::readMetaData(const int& ncid, std::vector<StationData>& vecStation)
{
356
	int vid_alt, vid_lat, vid_lon, vid_aspect, vid_slope, dimid;
357
358
	size_t dimlen;

359
	//HACK: could check dimension of all the vars, must be 'Number_of_points'
360
	get_dimension(ncid, cnrm_points, dimid, dimlen);
361
	get_variable(ncid, cnrm_altitude, vid_alt);
362
363
	get_variable(ncid, IOUtils::strToUpper(NetCDFIO::lat_str), vid_lat);
	get_variable(ncid, IOUtils::strToUpper(NetCDFIO::lon_str), vid_lon);
364
365
	get_variable(ncid, cnrm_aspect, vid_aspect);
	get_variable(ncid, cnrm_slope, vid_slope);
366
367
368
369

	double *alt = new double[dimlen];
	double *lat = new double[dimlen];
	double *lon = new double[dimlen];
370
371
	double *aspect = new double[dimlen];
	double *slope = new double[dimlen];
372
373
374
375

	read_data(ncid, "ZS", vid_alt, alt);
	read_data(ncid, NetCDFIO::lat_str, vid_lat, lat);
	read_data(ncid, NetCDFIO::lon_str, vid_lon, lon);
376
377
	read_data(ncid, NetCDFIO::lat_str, vid_aspect, aspect);
	read_data(ncid, NetCDFIO::lat_str, vid_slope, slope);
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394

	//Parse to StationData objects
	Coords location(coordin, coordinparam);
	ostringstream ss;
	string id, name;
	for (size_t ii=0; ii<dimlen; ii++) {
		location.setLatLon(lat[ii], lon[ii], alt[ii]);
		
		ss << (ii+1);
		id = ss.str();
		ss.str("");

		ss << "Station " << (ii +1);
		name = ss.str();
		ss.str("");
		
		StationData tmp(location, id, name);
395
396
		double aspect_bearing = (aspect[ii] < 0) ? 0 : aspect[ii]; // aspect allowed to be -1... HACK
		tmp.setSlope(slope[ii], aspect_bearing);
397
		vecStation.push_back(tmp);
398
399

		//cout << "Station " << (ii+1) << "  alt: " << alt[ii] << "  aspect: " << aspect_bearing << "  slope: " << slope[ii] << endl;
400
401
	}

402
	delete[] alt; delete[] lat; delete[] lon; delete[] aspect; delete[] slope;
403
404
}

405
void NetCDFIO::readMeteoData(const Date& dateStart, const Date& dateEnd, std::vector< std::vector<MeteoData> >& vecMeteo, const size_t&)
406
{
407
408
409
410
411
412
413
414
415
416
417
418
419
420
	vecMeteo.clear();

	string filename("");
	cfg.getValue("METEOFILE", "Input", filename);

	int ncid;
	open_file(filename, NC_NOWRITE, ncid);

	if (vecMetaData.empty()) readMetaData(ncid, vecMetaData);

	if (!vecMetaData.empty()) { //at least one station exists
		size_t index_start, index_end;
		vector<Date> vec_date;
		get_indices(ncid, dateStart, dateEnd, index_start, index_end, vec_date); //get indices for dateStart and dateEnd
421
422

		MeteoData meteo_data; //the template MeteoData object
423
		if ((index_start != IOUtils::npos) && (index_end != IOUtils::npos)) {
424
425
			map<string, size_t> map_parameters;
			get_parameters(ncid, map_parameters, meteo_data); //get a list of parameters present
426
			
427
			readData(ncid, index_start, vec_date, map_parameters, meteo_data, vecMeteo);
428
429
430
431
432
433
		}
	}

	close_file(filename, ncid);
}

434
435
void NetCDFIO::readData(const int& ncid, const size_t& index_start, const std::vector<Date>& vec_date, 
                        const std::map<std::string, size_t>& map_parameters, const MeteoData& meteo_data, std::vector< std::vector<MeteoData> >& vecMeteo)
436
437
438
{
	size_t number_of_stations = vecMetaData.size();
	size_t number_of_records = vec_date.size();
439

440
	//Allocate all the MeteoData objects
441
	vector<MeteoData> tmp_vec(number_of_records, meteo_data);
442
443
444
445
446
447
448
449
	for (size_t jj=0; jj<number_of_records; jj++) tmp_vec[jj].date = vec_date[jj]; //set correct date for every record

	for (size_t ii=0; ii<number_of_stations; ii++) {
		for (size_t jj=0; jj<number_of_records; jj++) tmp_vec[jj].meta = vecMetaData[ii]; //adapt meta data
		vecMeteo.push_back(tmp_vec);
	}

	//allocate enough linear space for each parameter
450
451
	map<string, double*> map_data;
	for (map<string, size_t>::const_iterator it = map_parameters.begin(); it != map_parameters.end(); it++) {
452
		double* data = new double[number_of_stations*number_of_records];
453
		const string& varname = it->first;
454

455
		map_data[varname] = data;
456
457
458
459
460
461

		int varid; 
		get_variable(ncid, varname, varid);
		read_data_2D(ncid, varname, varid, index_start, number_of_records, number_of_stations, data);
	}

462
	copy_data(ncid, map_parameters, map_data, number_of_stations, number_of_records, vecMeteo); 
463

464
	for (map<string, double*>::const_iterator it = map_data.begin(); it != map_data.end(); it++) {
465
466
467
468
		delete[] it->second;
	}
}

469
470
void NetCDFIO::copy_data(const int& ncid, const std::map<std::string, size_t>& map_parameters, const std::map<std::string, double*> map_data, 
                         const size_t& number_of_stations, const size_t& number_of_records, std::vector< std::vector<MeteoData> >& vecMeteo)
471
{
472
473
474
475
	for (map<string, double*>::const_iterator it = map_data.begin(); it != map_data.end(); it++) {
		const string& varname = it->first;

		//find correct handling for each parameter
476
		bool simple_copy = false, mutiply_copy = false, hnw_measurement = false, sw_measurement = false;
477
		double multiplier = IOUtils::nodata;
478
		size_t param = map_parameters.find(varname)->second; //must exist, at this point we know it does
479
480

		if (param == IOUtils::npos) {
481
482
			if ((varname == cnrm_snowf) || (varname == cnrm_hnw)) {
				int varid;
Thomas Egger's avatar
Thomas Egger committed
483
484
				get_variable(ncid, cnrm_timestep, varid);
				read_value(ncid, cnrm_timestep, varid, multiplier);
485
				
Thomas Egger's avatar
Thomas Egger committed
486
				if (multiplier <= 0) throw InvalidArgumentException("The variable '" + cnrm_timestep + "' is invalid", AT);
487
488
489
490

				hnw_measurement = true;
			} else if ((varname == cnrm_swr_diffuse) || (varname == cnrm_swr_direct)) {
				sw_measurement = true;
491
492
			} else {
				throw IOException("Don't know how to deal with parameter " + varname, AT);
493
494
			}
		} else {
495
			if (varname == cnrm_rh) {
496
497
498
499
500
501
502
				mutiply_copy = true;
				multiplier = 0.01;
			} else {
				simple_copy = true;
			}
		}

503
		for (size_t jj=0; jj<number_of_records; jj++) {
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
			for (size_t ii=0; ii<number_of_stations; ii++) {
				double& value = (it->second)[jj*number_of_stations + ii];
				bool nodata = false;

				if (value == plugin_nodata) {
					nodata = true;
					value = IOUtils::nodata;
				}

				if (simple_copy) {
					vecMeteo[ii][jj](param) = value;
				} else if (mutiply_copy) {
					if (nodata) {
						vecMeteo[ii][jj](param) = value;
					} else {
						vecMeteo[ii][jj](param) = value * multiplier;
					}
521
				} else if (hnw_measurement) {
522
					if (!nodata) {
523
						double& hnw = vecMeteo[ii][jj](MeteoData::HNW);
524
525
526
						if (hnw == IOUtils::nodata) hnw = 0.0;
						hnw += value * multiplier;
					}
527
528
529
530
531
532
				} else if (sw_measurement) {
					if (!nodata) {
						double& iswr = vecMeteo[ii][jj](MeteoData::ISWR);
						if (iswr == IOUtils::nodata) iswr = 0.0;
						iswr += value; 
					}
533
				}
534
535
536
537
538
			}
		}
	}
}

539
void NetCDFIO::get_parameters(const int& ncid, std::map<std::string, size_t>& map_parameters, MeteoData& meteo_data)
540
{
541
	for (map<string, size_t>::const_iterator it = paramname.begin(); it != paramname.end(); it++) {
542
		if (check_variable(ncid, it->first)) {
543
544
545
546
547
548
549
550
551
			const string& name = it->first;
			size_t index = it->second;

			//cout << "Found parameter: " << name << endl; 
			if ((name == cnrm_theorsw) || (name == cnrm_qair) || (name == cnrm_co2air) || (name == cnrm_neb)) {
			 	index = meteo_data.addParameter(name);
			}

			map_parameters[it->first] = index;
552
553
554
		}
	}

555
	//TODO: check dimensions?
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
}

void NetCDFIO::get_indices(const int& ncid, const Date& dateStart, const Date& dateEnd, size_t& indexStart, size_t& indexEnd, std::vector<Date>& vecDate)
{
	//get dimid for time
	int varid, dimid;
	size_t dimlen;
	get_dimension(ncid, NetCDFIO::cf_time, dimid, dimlen);
	get_variable(ncid, NetCDFIO::cf_time, varid);

	//get attributes, calculate offset date
	string units_str;
	NetCDFIO::TimeUnit unit_type;
	Date offset;
	get_attribute(ncid, NetCDFIO::cf_time, varid, NetCDFIO::cf_units, units_str);
	calculate_offset(units_str, unit_type, offset); //HACK: should only be exctracted once

	//read values, find indices
	double *time = new double[dimlen];
	read_data(ncid, NetCDFIO::cf_time, varid, time);

	bool start_found = false;
	indexStart = indexEnd = IOUtils::npos;

	//check whether search makes any sense
	bool search = true;
	if (dimlen > 0) {
		Date time_start(offset), time_end(offset);
	
		double start = time[0];
		double end = time[dimlen-1];

		if (unit_type == seconds) {
			start /= 86400;
			end   /= 86400;
		}
		time_start += Date(start, in_dflt_TZ);
		time_end += Date(end, in_dflt_TZ);

		if (time_start > dateEnd) search = false;
		if (time_end < dateStart) search = false;
	}

	if (search) {
		for (size_t ii=0; ii<dimlen; ii++) {
			if (unit_type == seconds) {
				time[ii] /= 86400;
			}

605
			Date tmp_date = offset + Date(time[ii], 0.0);
606
			
607
608
609
			// cout << ii << "  julian: " << time[ii];
			// cout << "\t" << tmp_date.toString(Date::ISO);
			// cout << "\t" << setprecision(15) << tmp_date.getModifiedJulianDate() << endl;
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
			
			if (!start_found && (dateStart <= tmp_date && tmp_date <= dateEnd)) {
				start_found = true;
				indexStart = ii;
			} else if (start_found && (tmp_date > dateEnd)) {
				indexEnd = ii-1;
				break;
			}

			if (start_found) vecDate.push_back(tmp_date);
		}

		if (start_found && (indexEnd == IOUtils::npos)) {
			indexEnd = dimlen-1;
		}
	}
626
627
628
629
630
631
632

	// cout << "vecDate:" << vecDate.size() << endl;
	// vector<Date>::iterator it;
	// for (it = vecDate.begin(); it != vecDate.end(); it++) {
	// 	cout << (*it).toString(Date::ISO) << "   tz: " << (*it).getTimeZone() << "    MJ: " << setprecision(15) << (*it).getModifiedJulianDate() << endl;
	// }

633
634
	//cout << dateStart.toString(Date::ISO) << "  -  " << dateEnd.toString(Date::ISO) << endl;
	//cout << "indexStart: " << indexStart << "  indexEnd: " << indexEnd << endl;
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657

	delete[] time;
}

void NetCDFIO::calculate_offset(const std::string& units, NetCDFIO::TimeUnit& time_unit, Date& offset)
{
	string tmp(units);
	size_t found_sec = units.find(NetCDFIO::cf_seconds);
	size_t found_day = units.find(NetCDFIO::cf_days);

	if (found_sec != string::npos) {
		time_unit = seconds;
		tmp = tmp.substr(found_sec + NetCDFIO::cf_seconds.size());
	} else if (found_day != string::npos) {
		time_unit = days;
		tmp = tmp.substr(found_day+ + NetCDFIO::cf_days.size());
	} else {
		throw InvalidFormatException("Variable '"+NetCDFIO::cf_time+"' has no valid attribute 'units'" , AT);
	}
	
	bool success = IOUtils::convertString(offset, tmp, in_dflt_TZ);
	if (!success) throw InvalidFormatException("Cannot parse time: " + tmp, AT);

658
659
	// cout << "Parsing : " << tmp << endl;
	// cout << offset.toString() << endl;
660
661
}

662
void NetCDFIO::writeMeteoData(const std::vector< std::vector<MeteoData> >& vecMeteo, const std::string&)
663
{
664
665
666
667
668
669
670
671
672
673
674
675
676
	size_t number_of_stations = vecMeteo.size();
	if (number_of_stations == 0) return; //Nothing to write

	size_t number_of_records = vecMeteo[0].size();

	string filename("");
	cfg.getValue("METEOFILE", "Output", filename);

	int ncid, did_time, vid_time, did_points;
	bool create_time = false, create_points = false, create_locations = false, create_variables = false;
	bool exists = IOUtils::fileExists(filename);

	double* dates;
Thomas Egger's avatar
Thomas Egger committed
677
678
679
680
681
682
	map<string, double*> map_data;
	map_data[IOUtils::strToUpper(NetCDFIO::lat_str)] = new double[number_of_stations];
	map_data[IOUtils::strToUpper(NetCDFIO::lon_str)] = new double[number_of_stations];
	map_data[cnrm_altitude] = new double[number_of_stations];
	map_data[cnrm_aspect] = new double[number_of_stations];
	map_data[cnrm_slope] = new double[number_of_stations];
683
684
685
686

	map<string, int> varid;
	map<size_t, string> map_param_name;

Thomas Egger's avatar
Thomas Egger committed
687
	get_parameters(vecMeteo, map_param_name, map_data, dates);
688
689
690
691
692
693
694
695
696
697
698

	if (exists) {
		open_file(filename, NC_WRITE, ncid);
		start_definitions(filename, ncid);
	} else {
		create_file(filename, NC_CLASSIC_MODEL, ncid);
		create_time = create_points = create_locations = create_variables = true;
	}

	if (create_time) create_time_dimension(ncid, did_time, vid_time);
	if (create_points) add_dimension(ncid, cnrm_points, number_of_stations, did_points);
Thomas Egger's avatar
Thomas Egger committed
699
700
	if (create_locations) create_meta_data(ncid, did_points, map_data, varid);
	if (create_variables) create_parameters(ncid, did_time, did_points, number_of_records, number_of_stations, map_param_name, map_data, varid);
701
702
703

	end_definitions(filename, ncid);

Thomas Egger's avatar
Thomas Egger committed
704
	copy_data(number_of_stations, number_of_records, vecMeteo, map_param_name, map_data);
705
706

	write_record(ncid, NetCDFIO::cf_time, vid_time, number_of_records, dates);
Thomas Egger's avatar
Thomas Egger committed
707
	for (map<string, double*>::const_iterator it = map_data.begin(); it != map_data.end(); it++) {
708
		const string& varname = it->first;
Thomas Egger's avatar
Thomas Egger committed
709
		write_data(ncid, varname, varid[varname], map_data[varname]);
710
711
712
713
714
715
716
717
718
719
720
721
722
723
		delete[] it->second;
	}

	close_file(filename, ncid);

	delete[] dates;
}

void NetCDFIO::copy_data(const size_t& number_of_stations, const size_t& number_of_records, const std::vector< std::vector<MeteoData> >& vecMeteo,
                         const std::map<size_t, std::string>& map_param_name, std::map<std::string, double*>& map_data_2D)
{
	for (map<size_t, string>::const_iterator it = map_param_name.begin(); it != map_param_name.end(); it++) {
		const size_t& param = it->first;
		const string& varname = it->second;
Thomas Egger's avatar
Thomas Egger committed
724
725
726

		bool simple_copy = false, multiply_copy = false;
		double multiplier = IOUtils::nodata;
727
728
729

		double* data = map_data_2D[varname];

Thomas Egger's avatar
Thomas Egger committed
730
731
732
733
734
735
736
737
738
739
		if (param == MeteoData::RH) {
			multiplier = 100.;
			multiply_copy = true;
		} else if (param == MeteoData::HNW) {
			multiply_copy = true;
			multiplier = 1./3600.;
		} else {
			simple_copy = true;
		}

740
741
		for (size_t ii=0; ii<number_of_stations; ii++) {
			for (size_t jj=0; jj<number_of_records; jj++) {
Thomas Egger's avatar
Thomas Egger committed
742
743
744
745
746
747
748
749
750
				const double& value = vecMeteo[ii][jj](param);
				
				if (value == IOUtils::nodata) {
					// do nothing, rely on the _FillValue
				} else if (simple_copy) {
					data[jj*number_of_stations + ii] = value;
				} else if (multiply_copy) {
					data[jj*number_of_stations + ii] = value * multiplier;
				}
751
752
753
754
755
756
757
758
759
760
761
			} 
		}
	}
}

void NetCDFIO::create_meta_data(const int& ncid, const int& did, std::map<std::string, double*>& map_data_1D, std::map<std::string, int>& varid)
{
	for (map<string, double*>::const_iterator it = map_data_1D.begin(); it != map_data_1D.end(); it++) {
		int vid;
		const string& varname = it->first;

Thomas Egger's avatar
Thomas Egger committed
762
763
764
765
766
		if (varname == cnrm_timestep) {
			add_0D_variable(ncid, cnrm_timestep, NC_DOUBLE, vid);
		} else {
			add_1D_variable(ncid, varname, NC_DOUBLE, did, vid);
		}
767
		add_attribute(ncid, vid, "_FillValue", plugin_nodata);
Thomas Egger's avatar
Thomas Egger committed
768
		add_attributes_for_variable(ncid, vid, varname);
769
770
771
772
773
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
803
804
805
806
807
808
809

		varid[varname] = vid;
	}
}

void NetCDFIO::create_parameters(const int& ncid, const int& did_time, const int& did_points, const size_t& number_of_records,
						   const size_t& number_of_stations, std::map<size_t, std::string>& map_param_name,
                                 std::map<std::string, double*>& map_data_2D, std::map<std::string, int>& varid)
{
	map<string, string>::const_iterator it_cnrm;
	
	for (map<size_t, string>::iterator it = map_param_name.begin(); it != map_param_name.end();) {
		string& varname = it->second;

		it_cnrm = map_name.find(varname);
		if (it_cnrm != map_name.end()) {
			const string& cnrm_name = it_cnrm->second;
			varname = cnrm_name;

			int vid;

			double* data = new double[number_of_records*number_of_stations];
			map_data_2D[cnrm_name] = data;

			add_2D_variable(ncid, cnrm_name, NC_DOUBLE, did_time, did_points, vid);
			add_attribute(ncid, vid, "_FillValue", plugin_nodata);
			add_attributes_for_variable(ncid, vid, varname);		

			varid[varname] = vid;
			it++;
		} else {
			map_param_name.erase(it++);
		}
	}	
}

void NetCDFIO::get_parameters(const std::vector< std::vector<MeteoData> >& vecMeteo, std::map<size_t, std::string>& map_param_name, std::map<std::string, double*>& map_data_1D, double*& dates)
{
	size_t number_of_records = vecMeteo[0].size();
	dates = new double[number_of_records];

Thomas Egger's avatar
Thomas Egger committed
810
	double interval = 0;
811
	for (size_t ii=0; ii<number_of_records; ii++) {
812
		//		cout << "Date: " << vecMeteo[0][ii].date.toString(Date::ISO) << "   tz: " << vecMeteo[0][ii].date.getTimeZone()<< "    MJ: " <<  setprecision(15) << vecMeteo[0][ii].date.getModifiedJulianDate() <<endl;
813
		dates[ii] = vecMeteo[0][ii].date.getModifiedJulianDate();
Thomas Egger's avatar
Thomas Egger committed
814
815

		if (ii == 1) interval = round((dates[ii] - dates[ii-1]) * 86400.);
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
	}

	size_t nr_of_parameters = 0;
	if (vecMeteo[0].size() > 0) nr_of_parameters = vecMeteo[0][0].getNrOfParameters();

	vector<bool> vec_param_in_use(nr_of_parameters, false);
	vector<string> vec_param_name(nr_of_parameters, "");

	//Check consistency, dates must be existent everywhere
	bool inconsistent = false;
	for (size_t ii=0; ii<vecMeteo.size(); ii++) {
		if (number_of_records != vecMeteo[ii].size()) inconsistent = true;
		for (size_t jj=0; jj<vecMeteo[ii].size(); jj++) {
			const MeteoData& meteo_data = vecMeteo[ii][jj];

			if (dates[jj] != meteo_data.date.getModifiedJulianDate()) inconsistent = true;

			if (jj == 0) {
				map_data_1D[IOUtils::strToUpper(NetCDFIO::lat_str)][ii] = meteo_data.meta.position.getLat();
				map_data_1D[IOUtils::strToUpper(NetCDFIO::lon_str)][ii] = meteo_data.meta.position.getLon();
				map_data_1D[cnrm_altitude][ii] = meteo_data.meta.position.getAltitude();
				map_data_1D[cnrm_slope][ii] = meteo_data.meta.getSlopeAngle();
				map_data_1D[cnrm_aspect][ii] = meteo_data.meta.getAzimuth();
			}

			//Check which parameters are in use
			for (size_t kk=0; kk<nr_of_parameters; kk++) {
				if (!vec_param_in_use[kk]){
					if (meteo_data(kk) != IOUtils::nodata){
						vec_param_in_use[kk] = true;
						vec_param_name[kk] = meteo_data.getNameForParameter(kk);
					}
				}
			}
		}
	}

	if (inconsistent) throw IOException("Inconsistent dates in vecMeteo between different stations", AT);

	for (size_t kk=0; kk<nr_of_parameters; kk++) {
		if (vec_param_in_use[kk])
			map_param_name[kk] = vec_param_name[kk];
	}
Thomas Egger's avatar
Thomas Egger committed
859
860
861
862
863


	double* timestep = new double[1];
	*timestep = interval;
	map_data_1D[cnrm_timestep] = timestep;
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
}

void NetCDFIO::readPOI(std::vector<Coords>&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void NetCDFIO::write2DGrid(const Grid2DObject& grid_in, const std::string& arguments)
{
	vector<string> vec_argument;
	IOUtils::readLineToVec(arguments, vec_argument, ':');

	if (vec_argument.size() != 2)
		throw InvalidArgumentException("The format for the arguments to NetCDFIO::write2DGrid is filename:varname", AT);

	const string& filename = vec_argument[0];
	const string& varname = vec_argument[1];

	bool exists = IOUtils::fileExists(filename);
	
	double *lat_array = new double[grid_in.nrows];
	double *lon_array = new double[grid_in.ncols];
	double *data = new double[grid_in.nrows * grid_in.ncols];

	calculate_dimensions(grid_in, lat_array, lon_array);
	fill_data(grid_in, data);

	int ncid, did_lat, did_lon, vid_lat, vid_lon, vid_var;
	bool create_dimensions(false), create_variable(false);

	if (exists) {
		open_file(filename, NC_WRITE, ncid);

		//check of lat/lon are defined and consistent
		if (check_dim_var(ncid, NetCDFIO::lat_str) && check_dim_var(ncid, NetCDFIO::lon_str)) {
			check_consistency(ncid, grid_in, lat_array, lon_array, did_lat, did_lon, vid_lat, vid_lon);
		} else {
			create_dimensions = true;
		}

		if (check_variable(ncid, varname)) { // variable exists
			get_variable(ncid, varname, vid_var);

			vector<int> dimid, dim_varid;
			vector<string> dimname;
			vector<size_t> dimlen;

			get_dimension(ncid, vec_argument[1], vid_var, dimid, dim_varid, dimname, dimlen);

			if ((dimname[0] != NetCDFIO::lat_str) || (dimname[1] != NetCDFIO::lon_str) || (dimlen[0]!=grid_in.nrows) || (dimlen[1]!=grid_in.ncols))
				throw IOException("Variable '" + vec_argument[1]  + "' already defined with different dimensions in file '"+ filename  +"'", AT);
		} else {
			create_variable = true;
		}

		start_definitions(filename, ncid);
	} else {
		create_file(filename, NC_CLASSIC_MODEL, ncid);
		add_attribute(ncid, NC_GLOBAL, "Conventions", "CF-1.3");

		create_variable = create_dimensions = true;
	}

	if (create_dimensions) create_latlon_dimensions(ncid, grid_in, did_lat, did_lon, vid_lat, vid_lon);

	if (create_variable) {
		add_2D_variable(ncid, vec_argument[1], NC_DOUBLE, did_lat, did_lon, vid_var);
		add_attributes_for_variable(ncid, vid_var, vec_argument[1]);
	}

	end_definitions(filename, ncid);

	if (create_dimensions) {
		write_data(ncid, NetCDFIO::lat_str, vid_lat, lat_array);
		write_data(ncid, NetCDFIO::lon_str, vid_lon, lon_array);
	}

	write_data(ncid, vec_argument[1], vid_var, data);

	close_file(filename, ncid);
	delete[] lat_array; delete[] lon_array; delete[] data;
}

void NetCDFIO::write2DGrid(const Grid2DObject& grid_in, const MeteoGrids::Parameters& parameter, const Date& date)
{
	string filename("");
	cfg.getValue("GRID2DFILE", "Output", filename);

	string varname = get_varname(parameter);
	bool exists = IOUtils::fileExists(filename);
	
	double *lat_array = new double[grid_in.nrows];
	double *lon_array = new double[grid_in.ncols];
	double *data = new double[grid_in.nrows * grid_in.ncols];

	calculate_dimensions(grid_in, lat_array, lon_array);
	fill_data(grid_in, data);

	int ncid, did_lat, did_lon, did_time, vid_lat, vid_lon, vid_var, vid_time;
	bool create_dimensions(false), create_variable(false), create_time(false);

	if (exists) {
		open_file(filename, NC_WRITE, ncid);

		//check of lat/lon are defined and consistent
		if (check_dim_var(ncid, NetCDFIO::lat_str) && check_dim_var(ncid, NetCDFIO::lon_str)) {
			check_consistency(ncid, grid_in, lat_array, lon_array, did_lat, did_lon, vid_lat, vid_lon);
		} else {
			create_dimensions = true;
		}

		//check if a time dimension/variable already exists
977
978
979
		if (check_dim_var(ncid, NetCDFIO::cf_time)) {
			get_dimension(ncid, NetCDFIO::cf_time, did_time);
			get_variable(ncid, NetCDFIO::cf_time, vid_time);			
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
		} else {
			create_time = true;
		}

		if (check_variable(ncid, varname)) { // variable exists
			get_variable(ncid, varname, vid_var); //HACK check dimensionality
		} else {
			create_variable = true;
		}

		start_definitions(filename, ncid);
	} else {
		create_file(filename, NC_CLASSIC_MODEL, ncid);
		add_attribute(ncid, NC_GLOBAL, "Conventions", "CF-1.3");

		create_variable = create_dimensions = create_time = true;
	}

	if (create_dimensions) create_latlon_dimensions(ncid, grid_in, did_lat, did_lon, vid_lat, vid_lon);
	if (create_time) create_time_dimension(ncid, did_time, vid_time);

For faster browsing, not all history is shown. View entire blame