WSL/SLF GitLab Repository

GrassIO.cc 9.36 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/***********************************************************************************/
/*  Copyright 2009 EPFL                                                            */
/***********************************************************************************/
/* 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 "GrassIO.h"

using namespace std;

namespace mio {
/**
 * @page grass GRASS
 * @section grass_format Format
 * This is for reading grid data in the JGRASS GIS format(see http://jgrass.wiki.software.bz.it/jgrass/JGrass_Wiki)
 *
 * @section grass_units Units
 * The distances are assumed to be in meters.
 *
 * @section grass_keywords Keywords
 * This plugin uses the following keywords:
 * - COORDSYS: input coordinate system (see Coords) specified in the [Input] section
 * - COORDPARAM: extra input coordinates parameters (see Coords) specified in the [Input] section
 * - COORDSYS: output coordinate system (see Coords) specified in the [Output] section
 * - COORDPARAM: extra output coordinates parameters (see Coords) specified in the [Output] section
 * - DEMFILE: for reading the data as a DEMObject
 * - LANDUSE: for interpreting the data as landuse codes
 * - DAPATH: path+prefix of file containing data assimilation grids (named with ISO 8601 basic date and .sca extension, example ./input/dagrids/sdp_200812011530.sca)
 */

const double GrassIO::plugin_nodata = -999.0; //plugin specific nodata value

44
GrassIO::GrassIO(void (*delObj)(void*), const Config& i_cfg) : IOInterface(delObj), cfg(i_cfg)
45
46
47
48
49
50
51
52
53
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
}

GrassIO::GrassIO(const std::string& configfile) : IOInterface(NULL), cfg(configfile)
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
}

54
GrassIO::GrassIO(const Config& cfgreader) : IOInterface(NULL), cfg(cfgreader)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
}

GrassIO::~GrassIO() throw()
{
	cleanup();
}

void GrassIO::cleanup() throw()
{
	if (fin.is_open()) {//close fin if open
		fin.close();
	}
	if (fout.is_open()) {//close fout if open
		fout.close();
	}
}

void GrassIO::read2DGrid(Grid2DObject& grid_out, const std::string& filename)
{

	int _nx, _ny;
	unsigned int ncols, nrows;
	double north, east, south, west;
	double tmp_val, xllcorner, yllcorner, cellsize;
	vector<string> tmpvec;
	std::string line="";
	std::map<std::string, std::string> header; // A map to save key value pairs of the file header

	if (!IOUtils::validFileName(filename)) {
		throw InvalidFileNameException(filename, AT);
	}
	if (!IOUtils::fileExists(filename)) {
		throw FileNotFoundException(filename, AT);
	}

	fin.clear();
	fin.open (filename.c_str(), ifstream::in);
	if (fin.fail()) {
		throw FileAccessException(filename, AT);
	}

	char eoln = IOUtils::getEoln(fin); //get the end of line character for the file

	//Go through file, save key value pairs
	try {
		IOUtils::readKeyValueHeader(header, fin, 6, ":");
		IOUtils::getValueForKey(header, "cols",  _nx);
		IOUtils::getValueForKey(header, "rows",  _ny);
		IOUtils::getValueForKey(header, "north", north);
		IOUtils::getValueForKey(header, "east",  east);
		IOUtils::getValueForKey(header, "south", south);
		IOUtils::getValueForKey(header, "west",  west);

		//HACK!! would it be possible for getValueForKey() to do this transparently? (with a user flag)
		_nx = IOUtils::standardizeNodata(_nx, plugin_nodata);
		_ny = IOUtils::standardizeNodata(_ny, plugin_nodata);
		north = IOUtils::standardizeNodata(north, plugin_nodata);
		east = IOUtils::standardizeNodata(east, plugin_nodata);
		south = IOUtils::standardizeNodata(south, plugin_nodata);
		west = IOUtils::standardizeNodata(west, plugin_nodata);

		if ((_nx==0) || (_ny==0)) {
			throw IOException("Number of rows or columns in 2D Grid given is zero, in file: " + filename, AT);
		}
		if((_nx<0) || (_ny<0)) {
			throw IOException("Number of rows or columns in 2D Grid read as \"nodata\", in file: " + filename, AT);
		}
		ncols = (unsigned int)_nx;
		nrows = (unsigned int)_ny;
		xllcorner = west;
		yllcorner = south;
		cellsize = (east - west) / (double)ncols;

		//compute WGS coordinates (considered as the true reference)
		Coords coordinate(coordin, coordinparam);
		coordinate.setXY(xllcorner, yllcorner, IOUtils::nodata);

		//Initialize the 2D grid
		grid_out.set(ncols, nrows, cellsize, coordinate);

		//Read one line after the other and parse values into Grid2DObject
		for (unsigned int kk=nrows-1; (kk < nrows); kk--) {
			getline(fin, line, eoln); //read complete line

			if (IOUtils::readLineToVec(line, tmpvec) != ncols) {
				throw InvalidFormatException("Premature End " + filename, AT);
			}

			for (unsigned int ll=0; ll < ncols; ll++){
				if (tmpvec[ll] == "*"){
					tmp_val = plugin_nodata;
				} else {
					if (!IOUtils::convertString(tmp_val, tmpvec[ll], std::dec)) {
						throw ConversionFailedException("For Grid2D value in line: " + line + " in file " + filename, AT);
					}
				}

				if(tmp_val <= plugin_nodata) {
					//replace file's nodata by uniform, internal nodata
					grid_out.grid2D(ll, kk) = IOUtils::nodata;
				} else {
					grid_out.grid2D(ll, kk) = tmp_val;
				}
			}
		}
162
	} catch(const std::exception&) {
163
164
165
166
167
168
		cleanup();
		throw;
	}
	cleanup();
}

169
170
171
172
173
174
175
void GrassIO::read2DGrid(Grid2DObject&, const MeteoGrids::Parameters&, const Date&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}


176
177
178
179
180
181
182
183
184
185
void GrassIO::readDEM(DEMObject& dem_out)
{
	string filename="";
	cfg.getValue("DEMFILE", "Input", filename);
	read2DGrid(dem_out, filename);
}

void GrassIO::readLanduse(Grid2DObject& landuse_out)
{
	string filename="";
186
	cfg.getValue("LANDUSEFILE", "Input", filename);
187
188
189
190
191
192
193
194
195
	read2DGrid(landuse_out, filename);
}

void GrassIO::readAssimilationData(const Date& date_in, Grid2DObject& da_out)
{
	int yyyy, MM, dd, hh, mm;
	date_in.getDate(yyyy, MM, dd, hh, mm);
	string filepath="";

196
	cfg.getValue("DAPATH", "Input", filepath);
197
198
199
200
201
202
203
204
205
206
207
208
209
210

	stringstream ss;
	ss.fill('0');
	ss << filepath << "/" << setw(4) << yyyy << setw(2) << MM << setw(2) <<  dd << setw(2) <<  hh << setw(2) <<  mm <<".sca";

	read2DGrid(da_out, ss.str());
}

void GrassIO::readStationData(const Date&, std::vector<StationData>&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

211
void GrassIO::readMeteoData(const Date&, const Date&, std::vector< std::vector<MeteoData> >&,
212
                            const size_t&)
213
214
215
216
217
218
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void GrassIO::writeMeteoData(const std::vector< std::vector<MeteoData> >&,
219
                             const std::string&)
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

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

void GrassIO::write2DGrid(const Grid2DObject& grid_in, const std::string& name)
{
	fout.open(name.c_str());
	if (fout.fail()) {
		throw FileAccessException(name, AT);
	}

	Coords llcorner=grid_in.llcorner;
	//we want to make sure that we are using the provided projection parameters
	//so that we output is done in the same system as the inputs
	llcorner.setProj(coordout, coordoutparam);

	fout << setprecision(6) << fixed;

	try {
246
247
248
249
250
251
		fout << "north:" << (llcorner.getNorthing()+grid_in.cellsize*grid_in.nrows) << "\n";
		fout << "south:" << llcorner.getNorthing() << "\n";
		fout << "east:"  << (llcorner.getEasting()+grid_in.cellsize*grid_in.ncols)  << "\n";
		fout << "west:"  << llcorner.getEasting() << "\n";
		fout << "rows:"  << grid_in.nrows << "\n";
		fout << "cols:"  << grid_in.ncols << "\n";
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

		for (unsigned int kk=grid_in.nrows-1; kk < grid_in.nrows; kk--) {
			unsigned int ll = 0;
			for (ll=0; ll < (grid_in.ncols-1); ll++){
				if (grid_in.grid2D(ll,kk) == IOUtils::nodata) {
					fout << "* ";
				} else {
					fout << grid_in.grid2D(ll, kk) << " ";
				}
			}

			//The last value in a line does not have a trailing " "
			if (grid_in.grid2D(ll,kk) == IOUtils::nodata) {
				fout << "*";
			} else {
				fout << grid_in.grid2D(ll, kk);
			}
269
			fout << "\n";
270
		}
271
	} catch(const std::exception& e) {
272
		cout << "[E] " << AT << ": " << e.what() << std::endl;
273
274
275
276
277
278
279
		cleanup();
		throw;
	}

	cleanup();
}

280
281
282
283
284
285
void GrassIO::write2DGrid(const Grid2DObject&, const MeteoGrids::Parameters&, const Date&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

286
287
288
#ifndef _METEOIO_JNI
extern "C"
{
289
290
291
#define COMPILE_PLUGIN
#include "exports.h"

292
	METEOIO_EXPORT void deleteObject(void* obj) {
293
294
295
		delete reinterpret_cast<PluginObject*>(obj);
	}

296

297
	METEOIO_EXPORT void* loadObject(const string& classname, const Config& cfg) {
298
299
		if(classname == "GrassIO") {
			//cerr << "Creating dynamic handle for " << classname << endl;
300
			return new GrassIO(deleteObject, cfg);
301
302
303
304
305
306
307
308
		}
		//cerr << "Could not load " << classname << endl;
		return NULL;
	}
}
#endif

} //namespace