WSL/SLF GitLab Repository

IOHandler.cc 14.6 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
19

#include <meteoio/IOHandler.h>
20
21
22
23
24
25
26
27
28
29
30
31

using namespace std;

namespace mio {
 /**
 * @page plugins Plugins overview
 * The data access is handled by a system of plugins. They all offer the same interface, meaning that a plugin can transparently be replaced by another one. Since they might rely on third party libraries for accessing the data, they have been created as plugins, that is they are loaded on demand (and also compiled only if requested at compile time). A plugin can therefore fail to load (for example if it does not exist) at run time.
 *
 * @section available_plugins Available plugins
 * So far the following children have been implemented (by keyword for the io.ini key/value config file). Please read the documentation for each plugin in order to know the plugin-specific keywords:
 * - \subpage a3d "A3D" for reading original Alpine3D meteo files (no extra requirements)
 * - \subpage borma "BORMA" for reading Borma xml meteo files (requires libxml)
32
 * - \subpage cosmoxml "COSMO" for treading XML files produced by MeteoSwiss COSMO's postprocessing (requires libxml)
33
34
35
36
37
38
39
40
 * - \subpage imis "IMIS" for reading meteo data out of the IMIS database (requires Oracle's OCCI library)
 * - \subpage geotop "GEOTOP" for reading original GeoTop meteo files (no extra requirements)
 * - \subpage snowpack "SNOWPACK" for reading original SNOWPACK meteo files (no extra requirements)
 * - \subpage gsn "GSN" for reading meteo data out of the Global Sensor Network web service interface (requires GSoap)
 * - \subpage arc "ARC" for reading ESRI/ARC DEM files (no extra requirements)
 * - \subpage grass "GRASS" for reading Grass DEM files (no extra requirements)
 * - \subpage arps "ARPSIO" for reading ARPS formatted DEM (no extra requirements)
 * - \subpage pgmio "PGMIO" for reading PGM grid files (no extra requirements)
41
 * - \subpage smetio "SMETIO" for reading SMET meteo data files (no extra requirements)
42
 *
Mathias Bavay's avatar
Mathias Bavay committed
43
44
45
46
47
48
49
50
51
 * @section data_generators Data generators
 * It is also possible to duplicate a meteorological parameter as another meteorological parameter. This is done by specifying a COPY key, following the syntax
 * COPY::new_name = existing_parameter. For example:
 * @code
 * COPY::VW_avg = VW
 * @endcode
 * This creates a new parameter VW_avg that starts as an exact copy of the raw data of VW, for each station. This newly created parameter is
 * then processed as any other meteorological parameter (thus going through filtering, generic processing, spatial interpolations). This only current
 * limitation is that the parameter providing the raw data must be defined for all stations (even if filled with nodata, this is good enough).
52
53
54
55
 */

void IOHandler::registerPlugins()
{
56
#if defined(_WIN32)
57
58
59
60
61
62
63
64
65
66
67
	const std::string libsuffix = ".dll";
#elif defined(APPLE)
	const std::string libsuffix = ".dylib";
#else
	const std::string libsuffix = ".so";
#endif
#ifdef _POPC_
	const std::string popc_extra = "popc";
#else
	const std::string popc_extra = "";
#endif
68
	//mapPlugins[io.ini KEY]= IOPlugin(library file name, class name, NULL, NULL);
69
70
71
72
73
	mapPlugins["A3D"]       = IOPlugin("", "A3DIO", &fileio, NULL);
	mapPlugins["BORMA"]     = IOPlugin("libbormaio"+popc_extra+libsuffix, "BormaIO", NULL, NULL);
	mapPlugins["IMIS"]      = IOPlugin("libimisio"+popc_extra+libsuffix, "ImisIO", NULL, NULL);
	mapPlugins["GEOTOP"]    = IOPlugin("libgeotopio"+popc_extra+libsuffix, "GeotopIO", NULL, NULL);
	mapPlugins["SNOWPACK"]  = IOPlugin("libsnio"+popc_extra+libsuffix, "SNIO", NULL, NULL);
74
75
76
77
78
79
	mapPlugins["GSN"]       = IOPlugin("libgsnio"+popc_extra+libsuffix, "GSNIO", NULL, NULL);
	mapPlugins["ARC"]       = IOPlugin("libarcio"+popc_extra+libsuffix, "ARCIO", NULL, NULL);
	mapPlugins["GRASS"]     = IOPlugin("libgrassio"+popc_extra+libsuffix, "GrassIO", NULL, NULL);
	mapPlugins["ARPS"]      = IOPlugin("libarpsio"+popc_extra+libsuffix, "ARPSIO", NULL, NULL);
	mapPlugins["PGM"]       = IOPlugin("libpgmio"+popc_extra+libsuffix, "PGMIO", NULL, NULL);
	mapPlugins["SMET"]      = IOPlugin("libsmetio"+popc_extra+libsuffix, "SMETIO", NULL, NULL);
80
	mapPlugins["COSMOXML"]  = IOPlugin("libcosmoxmlio"+popc_extra+libsuffix, "CosmoXMLIO", NULL, NULL);
81
82
83
}

#ifdef _POPC_
84
IOHandler::IOHandler(const std::string& configfile) :  cfg(configfile), fileio(configfile), enable_copying(false) {
85
#else
86
IOHandler::IOHandler(const std::string& configfile) : IOInterface(NULL), cfg(configfile), fileio(configfile),
87
                                                      enable_copying(false) {
88
#endif
89
	registerPlugins();
90
	parse_copy_config();
91
92
93
94
95
}

//Copy constructor
#ifdef _POPC_
//IOHandler::IOHandler(const IOHandler& aio) : cfg(aio.cfg), fileio(aio.cfg), bormaio(aio.cfg), imisio(aio.cfg){
96
	//Nothing else so far //HACK for POPC
97
98
//}
#else
99
IOHandler::IOHandler(const IOHandler& aio) : IOInterface(NULL), cfg(aio.cfg), fileio(aio.cfg), enable_copying(false)
100
101
102
103
104
105
106
{
	//Nothing else so far
	//TODO: Deal with the IOInterface* pointers, e.g. bormaio
}
#endif

#ifdef _POPC_
107
IOHandler::IOHandler(const Config& cfgreader) : cfg(cfgreader), fileio(cfgreader), enable_copying(false)
108
#else
109
IOHandler::IOHandler(const Config& cfgreader) : IOInterface(NULL), cfg(cfgreader), fileio(cfgreader), enable_copying(false)
110
111
112
#endif
{
	registerPlugins();
113
	parse_copy_config();
114
115
116
}

#ifdef _POPC_
117
IOHandler::~IOHandler(){
118
#else
119
IOHandler::~IOHandler() throw(){
120
121
#endif
	// Get rid of the objects
122
	std::map<std::string, IOPlugin>::iterator mapit;
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
	for (mapit = mapPlugins.begin(); mapit!=mapPlugins.end(); mapit++){
		deletePlugin((mapit->second).dynLibrary, (mapit->second).io);
	}
}
#ifdef _POPC_
void IOHandler::deletePlugin(DynamicLibrary*& dynLibrary, IOInterface*& io)
#else
void IOHandler::deletePlugin(DynamicLibrary*& dynLibrary, IOInterface*& io) throw()
#endif
{
	if (dynLibrary != NULL) {
		if (io != NULL) {
			io->deleteSelf();
			io = NULL;
		}

		// Close the dynamic library
#ifndef _POPC_ //HACK: this line causes a segfault in the parallel version for unknown reasons, lwk
		delete dynLibrary;
#endif
	}
}

void IOHandler::loadPlugin(const std::string& libname, const std::string& classname, DynamicLibrary*& dynLibrary, IOInterface*& io)
{
	std::string pluginpath = "";

	try {
151
		cfg.getValue("PLUGINPATH", pluginpath, Config::nothrow);
152
153
154
155
156
157
158
159
		if (pluginpath != "")
			pluginpath += "/";

		//Which dynamic library needs to be loaded
		std::string filename = pluginpath + libname;
		dynLibrary = DynamicLoader::loadObjectFile(filename);

		if(dynLibrary == NULL) {
160
161
162
			std::cout << AT << ": [E] Failed loading dynamic plugin " << classname << " from " << filename << std::endl;
			std::cout << "\t" << DynamicLoader::getErrorMessage() << std::endl;
			std::cout << "Please check your PLUGINPATH in your configuration file!" << std::endl;
163
		} else {
164
			io = dynamic_cast<IOInterface*>((dynLibrary)->newObject(classname, cfg));
165
166

			if(io == NULL) {
167
				std::cout << AT << ": [E] Failed loading dynamic plugin " << classname << " from " << filename << "(NULL pointer to plugin's class)" << std::endl;
168
169
				//delete dynLibrary; This causes a segfault !!
			} else {
170
				std::cout << "[i] Success loading dynamic plugin " << classname << " from " << filename << std::endl;
171
172
			}
		}
173
	} catch (const std::exception& e) {
174
	#ifndef _POPC_ //HACK: this line causes a segfault in the parallel version for unknown reasons, lwk
175
176
		if (dynLibrary != NULL)
			delete dynLibrary;
177
	#endif
178
		std::cerr << AT << ": [E] failed while loading plugin - " << e.what() << std::endl;
179
180
181
182
183
184
185
186
	}
}

IOInterface* IOHandler::getPlugin(const std::string& cfgkey, const std::string& cfgsection)
{
	std::string op_src="";
	cfg.getValue(cfgkey, cfgsection, op_src);

187
	std::map<std::string, IOPlugin>::iterator mapit = mapPlugins.find(op_src);
188
	if (mapit == mapPlugins.end())
189
		throw IOException("Can not find plugin " + op_src + " as requested in file " + cfg.getSourceName() + ". Has its developer declared it in IOHandler::registerPlugins?", AT);
190
191
192
193
194
195

	if ((mapit->second).io == NULL){
		loadPlugin((mapit->second).libname, (mapit->second).classname, (mapit->second).dynLibrary, (mapit->second).io);
	}

	if ((mapit->second).io == NULL) {
196
		throw IOException("Requesting to read/write data with plugin '" + op_src + "', but plugin is not loaded", AT);
197
198
199
200
201
	}

	return (mapit->second).io;
}

202
void IOHandler::read2DGrid(Grid2DObject& out_grid, const std::string& i_filename)
203
204
{
	IOInterface *plugin = getPlugin("GRID2D", "Input");
205
	plugin->read2DGrid(out_grid, i_filename);
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
}

void IOHandler::readDEM(DEMObject& dem_out)
{
	IOInterface *plugin = getPlugin("DEM", "Input");
	plugin->readDEM(dem_out);
	dem_out.update();
}

void IOHandler::readLanduse(Grid2DObject& landuse_out)
{
	IOInterface *plugin = getPlugin("LANDUSE", "Input");
	plugin->readLanduse(landuse_out);
}

221
void IOHandler::readStationData(const Date& date, STATION_TIMESERIE& vecStation)
222
223
224
225
226
{
	IOInterface *plugin = getPlugin("METEO", "Input");
	plugin->readStationData(date, vecStation);
}

227
void IOHandler::readMeteoData(const Date& date, METEO_TIMESERIE& vecMeteo)
228
229
230
231
{
	vecMeteo.clear();

	std::vector< std::vector<MeteoData> > meteoTmpBuffer;
232
	readMeteoData(date, date, meteoTmpBuffer);
233
234
235

	unsigned int emptycounter = 0;
	for (unsigned int ii=0; ii<meteoTmpBuffer.size(); ii++){//stations
236
		if (meteoTmpBuffer[ii].size() > 0){
237
238
239
240
241
242
243
244
245
246
247
248
			vecMeteo.push_back(meteoTmpBuffer[ii][0]);
		} else {
			emptycounter++;
		}
	}

	if (emptycounter == meteoTmpBuffer.size()){
		vecMeteo.clear();
	}
}

void IOHandler::readMeteoData(const Date& dateStart, const Date& dateEnd,
249
                              std::vector<METEO_TIMESERIE>& vecMeteo,
250
                              const size_t& stationindex)
251
252
{
	IOInterface *plugin = getPlugin("METEO", "Input");
253
	plugin->readMeteoData(dateStart, dateEnd, vecMeteo, stationindex);
254
255

	copy_parameters(stationindex, vecMeteo);
256
}
257
258
259
260
#ifdef _POPC_
void IOHandler::writeMeteoData(std::vector<METEO_TIMESERIE>& vecMeteo,
                               const std::string& name)
#else
261
void IOHandler::writeMeteoData(const std::vector<METEO_TIMESERIE>& vecMeteo,
262
                               const std::string& name)
263
#endif
264
265
{
	IOInterface *plugin = getPlugin("METEO", "Output");
266
	plugin->writeMeteoData(vecMeteo, name);
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
}

void IOHandler::readAssimilationData(const Date& date_in, Grid2DObject& da_out)
{
	IOInterface *plugin = getPlugin("DA", "Input");
	plugin->readAssimilationData(date_in, da_out);
}

void IOHandler::readSpecialPoints(std::vector<Coords>& pts) {
	IOInterface *plugin = getPlugin("SPECIALPTS", "Input");
	plugin->readSpecialPoints(pts);
}

void IOHandler::write2DGrid(const Grid2DObject& grid_in, const std::string& name)
{
	IOInterface *plugin = getPlugin("GRID2D", "Output");
	plugin->write2DGrid(grid_in, name);
}

286
287
288
void IOHandler::parse_copy_config()
{
	/**
289
	 * Parse [Input] section for potential parameters that the user wants
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
317
318
319
320
	 * duplicated (starting with 'COPY::')
	 */
	vector<string> copy_keys;
	size_t nrOfMatches = cfg.findKeys(copy_keys, "COPY::", "Input");

	for (size_t ii=0; ii<nrOfMatches; ii++) {
		string initial_name = "";
		string name_of_copy = copy_keys[ii].substr(6);
		cfg.getValue(copy_keys[ii], "Input", initial_name);

		if ((name_of_copy.length() > 0) && (initial_name.length() > 0)){
			copy_parameter.push_back(initial_name);
			copy_name.push_back(name_of_copy);
			//cout << "Param: " << initial_name << " copied to name: " << name_of_copy << endl;
			enable_copying = true;
		}
	}
}

void IOHandler::copy_parameters(const size_t& stationindex, std::vector< METEO_TIMESERIE >& vecMeteo) const
{
	/**
	 * This procedure runs through the MeteoData objects in vecMeteo and according to user
	 * configuration copies a certain present meteo parameter to another one, named by the
	 * user in the [Input] section of the io.ini, e.g.
	 * [Input]
	 * COPY::TA2 = TA
	 * means that TA2 will be the name of a new parameter in MeteoData with the copied value
	 * of the meteo parameter MeteoData::TA
	 */
	if (!enable_copying) return; //Nothing configured
321

322
323
324
325
326
327
328
	size_t station_start=0, station_end=vecMeteo.size();
	if (stationindex != IOUtils::npos) {
		if (stationindex < vecMeteo.size()) {
			station_start = stationindex;
			station_end   = stationindex+1;
		} else {
			throw IndexOutOfBoundsException("Accessing stationindex in readMeteoData that is out of bounds", AT);
329
		}
330
331
332
333
334
335
336
337
338
339
340
	}

	size_t nr_of_params = copy_parameter.size();
	vector<size_t> indices; //will hold the indices of the parameters to be copied

	for (size_t ii=station_start; ii<station_end; ii++) { //for each station
		for (size_t jj=0; jj<vecMeteo[ii].size(); jj++) { //for each MeteoData object of one station

			if (jj==0) { //buffer the index numbers
				for (size_t kk=0; kk<nr_of_params; kk++) {
					size_t param_index = vecMeteo[ii][jj].getParameterIndex(copy_parameter[kk]);
341
342
343
344
345
346
					if (param_index == IOUtils::npos) {
						std::stringstream ss;
						ss << "At " << vecMeteo[ii][jj].date.toString(Date::ISO) << ", station " << vecMeteo[ii][jj].meta.stationID;
						ss << " has no parameter \"" << copy_parameter[kk] << "\" to copy!\n";
						throw InvalidArgumentException(ss.str(), AT);
					}
347
348
349
350
351
352
353
354
355
356
357
358
359
360

					indices.push_back(param_index);
				}
			}

			for (size_t kk=0; kk<nr_of_params; kk++) {
				size_t newindex = vecMeteo[ii][jj].addParameter(copy_name[kk]);
				vecMeteo[ii][jj](newindex) = vecMeteo[ii][jj](indices[kk]);
			}
		}
		indices.clear(); //may change for every station
	}
}

361
#ifndef _POPC_
362
363
std::ostream& operator<<(std::ostream& os, const IOHandler& data)
{
364
365
366
367
368
369
370
371
372
373
374
375
	os << data.toString();
	return os;
}
#endif

#ifdef _POPC_
std::string IOHandler::toString()
#else
std::string IOHandler::toString() const
#endif
{
	std::stringstream os;
376
	os << "<IOHandler>\n";
377
	os << "Config cfg = " << hex << &cfg << dec << "\n";
378
379
380

	os << "<mapPlugins>\n";
	os << setw(10) << "Keyword" << " = " << IOPlugin::header << "\n";
381
	std::map<std::string, IOPlugin>::const_iterator it1;
382
	for (it1=mapPlugins.begin(); it1 != mapPlugins.end(); it1++){
383
384
385
386
		os << setw(10) << it1->first << " = " <<  it1->second;
	}
	os << "</mapPlugins>\n";
	os << "</IOHandler>\n";
387
	return os.str();
388
389
}

390
} //end namespace