WSL/SLF GitLab Repository

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

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

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
18
#include <cmath>
19
#include <limits.h>
20

21
#include <meteoio/DEMObject.h>
22
#include <meteoio/MathOptim.h>
23
#include <meteoio/meteolaws/Meteoconst.h> //for math constants
24

25
26
27
28
29
30
31
32
33
34
35
36
/**
* @file DEMObject.cc
* @brief implementation of the DEMBoject class
*/

using namespace std;

namespace mio {

/**
* @brief Default constructor.
* Initializes all variables to 0, except lat/long which are initialized to IOUtils::nodata
37
* @param i_algorithm specify the default algorithm to use for slope computation (default=DFLT)
38
*/
39
40
DEMObject::DEMObject(const slope_type& i_algorithm)
           : Grid2DObject(), slope(), azi(), curvature(), Nx(), Ny(), Nz(),
41
42
             min_altitude(Cst::dbl_max), min_slope(Cst::dbl_max), min_curvature(Cst::dbl_max),
             max_altitude(Cst::dbl_min), max_slope(Cst::dbl_min), max_curvature(Cst::dbl_min),
43
44
45
             CalculateSlope(&DEMObject::CalculateCorripio),
             update_flag(INT_MAX), dflt_algorithm(i_algorithm),
             slope_failures(0), curvature_failures(0)
46
{
47
	setDefaultAlgorithm(i_algorithm);
48
49
50
51
}

/**
* @brief Constructor that sets variables.
Mathias Bavay's avatar
Mathias Bavay committed
52
53
54
* @param i_ncols number of colums in the grid2D
* @param i_nrows number of rows in the grid2D
* @param i_cellsize value for cellsize in grid2D
55
56
* @param i_llcorner lower lower corner point
* @param i_algorithm specify the default algorithm to use for slope computation (default=DFLT)
57
*/
Mathias Bavay's avatar
Mathias Bavay committed
58
DEMObject::DEMObject(const size_t& i_ncols, const size_t& i_nrows,
59
                     const double& i_cellsize, const Coords& i_llcorner, const slope_type& i_algorithm)
60
61
           : Grid2DObject(i_ncols, i_nrows, i_cellsize, i_llcorner),
             slope(), azi(), curvature(), Nx(), Ny(), Nz(),
62
63
             min_altitude(Cst::dbl_max), min_slope(Cst::dbl_max), min_curvature(Cst::dbl_max),
             max_altitude(Cst::dbl_min), max_slope(Cst::dbl_min), max_curvature(Cst::dbl_min),
64
65
66
             CalculateSlope(&DEMObject::CalculateCorripio),
             update_flag(INT_MAX), dflt_algorithm(i_algorithm),
             slope_failures(0), curvature_failures(0)
67
{
68
	setDefaultAlgorithm(i_algorithm);
69
70
71
72
}

/**
* @brief Constructor that sets variables.
Mathias Bavay's avatar
Mathias Bavay committed
73
74
75
* @param i_ncols number of colums in the grid2D
* @param i_nrows number of rows in the grid2D
* @param i_cellsize value for cellsize in grid2D
76
* @param i_llcorner lower lower corner point
Mathias Bavay's avatar
Mathias Bavay committed
77
78
* @param i_altitude grid2D of elevations
* @param i_update also update slope/normals/curvatures and their min/max? (default=true)
79
* @param i_algorithm specify the default algorithm to use for slope computation (default=DFLT)
80
*/
Mathias Bavay's avatar
Mathias Bavay committed
81
DEMObject::DEMObject(const size_t& i_ncols, const size_t& i_nrows,
82
83
                     const double& i_cellsize, const Coords& i_llcorner, const Array2D<double>& i_altitude,
                     const bool& i_update, const slope_type& i_algorithm)
84
85
           : Grid2DObject(i_ncols, i_nrows, i_cellsize, i_llcorner, i_altitude),
             slope(), azi(), curvature(), Nx(), Ny(), Nz(),
86
87
             min_altitude(Cst::dbl_max), min_slope(Cst::dbl_max), min_curvature(Cst::dbl_max),
             max_altitude(Cst::dbl_min), max_slope(Cst::dbl_min), max_curvature(Cst::dbl_min),
88
89
90
             CalculateSlope(&DEMObject::CalculateCorripio),
             update_flag(INT_MAX), dflt_algorithm(i_algorithm),
             slope_failures(0), curvature_failures(0)
91
{
92
93
	setDefaultAlgorithm(i_algorithm);
	if(i_update==false) {
94
95
		updateAllMinMax();
	} else {
96
		update(i_algorithm);
97
98
99
100
101
	}
}

/**
* @brief Constructor that sets variables from a Grid2DObject
Mathias Bavay's avatar
Mathias Bavay committed
102
103
* @param i_dem grid contained in a Grid2DObject
* @param i_update also update slope/normals/curvatures and their min/max? (default=true)
104
* @param i_algorithm specify the default algorithm to use for slope computation (default=DFLT)
105
*/
106
DEMObject::DEMObject(const Grid2DObject& i_dem, const bool& i_update, const slope_type& i_algorithm)
107
108
           : Grid2DObject(i_dem.ncols, i_dem.nrows, i_dem.cellsize, i_dem.llcorner, i_dem.grid2D),
             slope(), azi(), curvature(), Nx(), Ny(), Nz(),
109
110
             min_altitude(Cst::dbl_max), min_slope(Cst::dbl_max), min_curvature(Cst::dbl_max),
             max_altitude(Cst::dbl_min), max_slope(Cst::dbl_min), max_curvature(Cst::dbl_min),
111
112
113
             CalculateSlope(&DEMObject::CalculateCorripio),
             update_flag(INT_MAX), dflt_algorithm(i_algorithm),
             slope_failures(0), curvature_failures(0)
114
{
115
116
	setDefaultAlgorithm(i_algorithm);
	if(i_update==false) {
117
118
		updateAllMinMax();
	} else {
119
		update(i_algorithm);
120
121
122
123
	}
}

/**
124
* @brief Constructor that sets variables from a subset of another DEMObject,
125
* given an origin (X,Y) (first index being 0) and a number of columns and rows
Mathias Bavay's avatar
Mathias Bavay committed
126
127
128
129
130
131
* @param i_dem dem contained in a DEMDObject
* @param i_nx X coordinate of the new origin
* @param i_ny Y coordinate of the new origin
* @param i_ncols number of columns for the subset dem
* @param i_nrows number of rows for the subset dem
* @param i_update also update slope/normals/curvatures and their min/max? (default=true)
132
* @param i_algorithm specify the default algorithm to use for slope computation (default=DFLT)
133
*/
Mathias Bavay's avatar
Mathias Bavay committed
134
135
DEMObject::DEMObject(const DEMObject& i_dem, const size_t& i_nx, const size_t& i_ny,
                     const size_t& i_ncols, const size_t& i_nrows,
136
                     const bool& i_update, const slope_type& i_algorithm)
137
138
           : Grid2DObject(i_dem, i_nx,i_ny, i_ncols,i_nrows),
             slope(), azi(), curvature(), Nx(), Ny(), Nz(),
139
140
             min_altitude(Cst::dbl_max), min_slope(Cst::dbl_max), min_curvature(Cst::dbl_max),
             max_altitude(Cst::dbl_min), max_slope(Cst::dbl_min), max_curvature(Cst::dbl_min),
141
142
143
             CalculateSlope(&DEMObject::CalculateCorripio),
             update_flag(i_dem.update_flag), dflt_algorithm(i_algorithm),
             slope_failures(0), curvature_failures(0)
144
{
145
	if ((i_ncols==0) || (i_nrows==0)) {
146
147
		throw InvalidArgumentException("requesting a subset of 0 columns or rows for DEMObject", AT);
	}
148

149
	//handling of the update properties
150
151
	setDefaultAlgorithm(i_algorithm);
	if(i_update==true) {
152
153
		//if the object is in automatic update, then we only process the arrays according to
		//the update_flag
154
		update(i_algorithm);
155
156
157
	} else {
		//if the object is NOT in automatic update, we manually copy all non-empty arrays
		//from the original set
Mathias Bavay's avatar
Mathias Bavay committed
158
		size_t nx, ny;
159

160
		i_dem.slope.size(nx, ny);
161
		if(nx>0 && ny>0) {
162
			slope.subset(i_dem.slope,i_nx,i_ny, i_ncols,i_nrows);
163
		}
164
		i_dem.azi.size(nx, ny);
165
		if(nx>0 && ny>0) {
166
			azi.subset(i_dem.azi,i_nx,i_ny, i_ncols,i_nrows);
167
		}
168
		i_dem.curvature.size(nx, ny);
169
		if(nx>0 && ny>0) {
170
			curvature.subset(i_dem.curvature,i_nx,i_ny, i_ncols,i_nrows);
171
		}
172
		i_dem.Nx.size(nx, ny);
173
		if(nx>0 && ny>0) {
174
			Nx.subset(i_dem.Nx,i_nx,i_ny, i_ncols,i_nrows);
175
		}
176
		i_dem.Ny.size(nx, ny);
177
		if(nx>0 && ny>0) {
178
			Ny.subset(i_dem.Ny,i_nx,i_ny, i_ncols,i_nrows);
179
		}
180
		i_dem.Nz.size(nx, ny);
181
		if(nx>0 && ny>0) {
182
			Nz.subset(i_dem.Nz,i_nx,i_ny, i_ncols,i_nrows);
183
184
185
		}

		updateAllMinMax();
186
187
188
	}
}

189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
* @brief Set the properties that will be calculated by the object when updating
* The following properties can be turned on/off: slope/azimuth and/or normals, and/or curvatures.
* Flags are combined using the binary "|" operator.
* @param in_update_flag parameters to update
*/
void DEMObject::setUpdatePpt(const update_type& in_update_flag) {
	update_flag = in_update_flag;
}

/**
* @brief Get the properties that will be calculated by the object when updating
* @return combination of flags set with the binary "|" operator
*/
203
int DEMObject::getUpdatePpt() const {
204
205
206
	return update_flag;
}

207
208
/**
* @brief Force the computation of the local slope, azimuth, normal vector and curvature.
209
* It has to be called manually since it can require some time to compute. Without this call,
210
* the above mentionned parameters are NOT up to date.
Mathias Bavay's avatar
Mathias Bavay committed
211
* @param algorithm algorithm to use for computing slope, azimuth and normals
212
213
*/
void DEMObject::update(const slope_type& algorithm) {
214
//This method recomputes the attributes that are not read as parameters
215
216
217
//(such as slope, azimuth, normal vector)

	// Creating tables
218
219
220
221
222
223
224
225
226
227
228
229
	if(update_flag&SLOPE) {
		slope.resize(ncols, nrows);
		azi.resize(ncols, nrows);
	}
	if(update_flag&CURVATURE) {
		curvature.resize(ncols, nrows);
	}
	if(update_flag&NORMAL) {
		Nx.resize(ncols, nrows);
		Ny.resize(ncols, nrows);
		Nz.resize(ncols, nrows);
	}
230
231
232
233
234
235
236

	CalculateAziSlopeCurve(algorithm);
	updateAllMinMax();
}

/**
* @brief Force the computation of the local slope, azimuth, normal vector and curvature.
237
* It has to be called manually since it can require some time to compute. Without this call,
238
* the above mentionned parameters are NOT up to date.
Mathias Bavay's avatar
Mathias Bavay committed
239
* @param algorithm algorithm to use for computing slope, azimuth and normals
240
241
242
243
244
245
* it is either:
* - HICK that uses the maximum downhill slope method (Dunn and Hickey, 1998)
* - FLEMING uses a 4 neighbors algorithm (Fleming and Hoffer, 1979)
* - CORRIPIO that uses the surface normal vector using the two triangle method given in Corripio (2002)
* and the eight-neighbor algorithm of Horn (1981) for border cells.
* - D8 uses CORRIPIO but discretizes the resulting azimuth to 8 cardinal directions and the slope is rounded to the nearest degree. Curvature and normals are left untouched.
246
*
247
248
249
* The azimuth is always computed using the Hodgson (1998) algorithm.
*/
void DEMObject::update(const std::string& algorithm) {
250
//This method recomputes the attributes that are not read as parameters
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//(such as slope, azimuth, normal vector)
	slope_type type;

	if(algorithm.compare("HICK")==0) {
		type=HICK;
	} else if(algorithm.compare("FLEMING")==0) {
		type=FLEM;
	} else if(algorithm.compare("HORN")==0) {
		type=HORN;
	} else if(algorithm.compare("CORRIPIO")==0) {
		type=CORR;
	} else if(algorithm.compare("D8")==0) {
		type=D8;
	} else if(algorithm.compare("DEFAULT")==0) {
		type=DFLT;
	} else {
		throw InvalidArgumentException("Chosen slope algorithm " + algorithm + " not available", AT);
	}
269

270
271
272
273
274
	update(type);
}

/**
* @brief Sets the default slope calculation algorithm
275
* @param i_algorithm specify the default algorithm to use for slope computation
276
*/
277
void DEMObject::setDefaultAlgorithm(const slope_type& i_algorithm) {
278
//This method MUST be called by each constructor!
279
	if(i_algorithm==DFLT) {
280
281
		dflt_algorithm = CORR;
	} else {
282
		dflt_algorithm = i_algorithm;
283
284
285
	}
}

286
287
288
289
290
291
292
/**
* @brief Get the default slope calculation algorithm
* @return default algorithm to use for slope computation
*/
int DEMObject::getDefaultAlgorithm() const {
	return dflt_algorithm;
}
293
294
/**
* @brief Recomputes the min/max of altitude, slope and curvature
295
* It return +/- std::numeric_limits\<double\>\:\:max() for a given parameter if its grid was empty/undefined
296
297
298
*/
void DEMObject::updateAllMinMax() {
//updates the min/max parameters of all 2D tables
299
	if(update_flag&SLOPE) {
300
301
		min_slope = slope.getMin();
		max_slope = slope.getMax();
302
303
	}
	if(update_flag&CURVATURE) {
304
305
		min_curvature = curvature.getMin();
		max_curvature = curvature.getMax();
306
307
	}

308
309
	min_altitude = grid2D.getMin();
	max_altitude = grid2D.getMax();
310
311
312
313
314
315
316
317
318
319
}

/**
* @brief Prints the list of points that have an elevation different than nodata but no slope or curvature
* Such points can happen if they are surrounded by too many points whose elevation is nodata
* If no such points exist, it prints nothing.
*/
void DEMObject::printFailures() {
	bool header=true;

320
	if(update_flag&SLOPE) {
Mathias Bavay's avatar
Mathias Bavay committed
321
322
		for ( size_t j = 0; j < nrows; j++ ) {
			for ( size_t i = 0; i < ncols; i++ ) {
323
324
				if((slope(i,j)==IOUtils::nodata) && (grid2D(i,j)!=IOUtils::nodata)) {
					if(header==true) {
325
326
						cerr << "[i] DEM slope could not be computed at the following points \n";
						cerr << "[i]\tGrid Point\tElevation\tSlope\n";
327
328
						header=false;
					}
329
					cerr << "[i]\t(" << i << "," << j << ")" << "\t\t" << grid2D(i,j) << "\t\t" << slope(i,j) << "\n";
330
331
332
333
334
335
				}
			}
		}
	}

	if(update_flag&CURVATURE) {
Mathias Bavay's avatar
Mathias Bavay committed
336
337
		for ( size_t j = 0; j < nrows; j++ ) {
			for ( size_t i = 0; i < ncols; i++ ) {
338
339
				if((curvature(i,j)==IOUtils::nodata) && (grid2D(i,j)!=IOUtils::nodata)) {
					if(header==true) {
340
341
						cerr << "[i] DEM curvature could not be computed at the following points \n";
						cerr << "[i]\tGrid Point\tElevation\tCurvature\n";
342
343
						header=false;
					}
344
					cerr << "[i]\t(" << i << "," << j << ")" << "\t\t" << grid2D(i,j) << "\t\t" <<  curvature(i,j) << "\n";
345
346
347
348
349
				}
			}
		}
	}
	if(header==false) {
350
		cerr << std::endl;
351
352
353
354
355
356
357
358
359
360
361
362
363
364
	}
}

/**
* @brief Clean up the DEM Object
* When computing the slope and curvature, it is possible to get points where the elevation is known
* but where no slope/azimuth/normals/curvature could be computed. This method sets the elevation to nodata for such points,
* so that latter use of the DEM would be simpler (simply test the elevation in order to know if the point can be used
* and it guarantees that all other informations are available).If the slope/azimuth/normals/curvature tables were manually updated, this method will NOT perform any work (it requires the count of slopes/curvature failures to be greater than zero)
*
* IMPORTANT: calling this method DOES change the table of elevations!
*/
void DEMObject::sanitize() {
	if(slope_failures>0 || curvature_failures>0) {
Mathias Bavay's avatar
Mathias Bavay committed
365
366
		for ( size_t j = 0; j < nrows; j++ ) {
			for ( size_t i = 0; i < ncols; i++ ) {
367
368
369
370
371
372
373
374
375
				if(update_flag&SLOPE) {
					if((slope(i,j)==IOUtils::nodata) && (grid2D(i,j)!=IOUtils::nodata)) {
						grid2D(i,j) = IOUtils::nodata;
					}
				}
				if(update_flag&CURVATURE) {
					if((curvature(i,j)==IOUtils::nodata) && (grid2D(i,j)!=IOUtils::nodata)) {
						grid2D(i,j) = IOUtils::nodata;
					}
376
377
378
379
380
381
				}
			}
		}
	}
}

382
383
384
385
386
/**
* @brief Computes the hillshade for the dem
* This "fake illumination" method is used to better show the relief on maps.
* @param elev elevation (in degrees) of the source of light
* @param azimuth azimuth (in degrees) of the source of light
387
* @return hillshade grid that containing the illumination
388
389
*
*/
390
Grid2DObject DEMObject::getHillshade(const double& elev, const double& azimuth) const
391
{
392
	Grid2DObject hillshade(ncols, nrows, cellsize, llcorner);
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

	if(slope.isEmpty() || azi.isEmpty())
		throw InvalidArgumentException("Hillshade computation requires slope and azimuth!", AT);

	const double zenith_rad = (90.-elev)*Cst::to_rad;
	const double azimuth_rad = azimuth*Cst::to_rad;

	for ( size_t j = 0; j < nrows; j++ ) {
		for ( size_t i = 0; i < ncols; i++ ) {
			const double alt = grid2D(i,j);
			const double sl = slope(i,j);
			const double az = azi(i,j);
			if(alt!=IOUtils::nodata && sl!=IOUtils::nodata && az!=IOUtils::nodata) {
				const double sl_rad = sl*Cst::to_rad;
				const double tmp = cos(zenith_rad) * cos(sl_rad) + sin(zenith_rad) * sin(sl_rad) * cos(azimuth_rad-az*Cst::to_rad);
				hillshade(i,j) = (tmp>=0.)? tmp : 0.;
			} else
				hillshade(i,j) = IOUtils::nodata;
		}
	}
413
414

	return hillshade;
415
416
}

417
418
419
420
421
422
423
424
425
426
427
/**
* @brief Computes the horizontal distance between two points in a metric grid
* @param xcoord1 east coordinate of the first point
* @param ycoord1 north coordinate of the first point
* @param xcoord2 east coordinate of the second point
* @param ycoord2 north coordinate of the second point
* @return horizontal distance in meters
*
*/
double DEMObject::horizontalDistance(const double& xcoord1, const double& ycoord1, const double& xcoord2, const double& ycoord2)
{
428
	return sqrt( Optim::pow2(xcoord2-xcoord1) + Optim::pow2(ycoord2-ycoord1) );
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
}

/**
* @brief Computes the horizontal distance between two points in a metric grid
* @param point1 first point (ie: origin)
* @param point2 second point (ie: destination)
* @return horizontal distance in meters
*
*/
double DEMObject::horizontalDistance(Coords point1, const Coords& point2)
{
	if(point1.isSameProj(point2)==false) {
		point1.copyProj(point2);
	}
	return horizontalDistance(point1.getEasting(), point1.getNorthing(),
444
	                          point2.getEasting(), point2.getNorthing() );
445
446
447
448
449
450
451
452
453
454
455
456
457
}


/**
* @brief Returns the distance *following the terrain* between two coordinates
* @param point1 first point (ie: origin)
* @param point2 second point (ie: destination)
* @return distance following the terrain in meters
*
*/
double DEMObject::terrainDistance(Coords point1, const Coords& point2) {
	std::vector<GRID_POINT_2D> vec_points;
	double distance=0.;
Mathias Bavay's avatar
Mathias Bavay committed
458
	size_t last_point=0; //point 0 is always the starting point
459
460
461
462
463
464
465

	//Checking that both points use the same projection is done in getPointsBetween()
	getPointsBetween(point1, point2, vec_points);
	if(vec_points.size()<=1) {
		return 0.;
	}

Mathias Bavay's avatar
Mathias Bavay committed
466
467
468
469
470
	for(size_t ii=1; ii<vec_points.size(); ii++) {
		const size_t ix1=vec_points[last_point].ix;
		const size_t iy1=vec_points[last_point].iy;
		const size_t ix2=vec_points[ii].ix;
		const size_t iy2=vec_points[ii].iy;
471
472
473
474
475
476

		if(grid2D(ix2,iy2)!=IOUtils::nodata) {
			if(grid2D(ix1,iy1)!=IOUtils::nodata) {
				//distance += sqrt( pow2((ix2-ix1)*cellsize) + pow2((iy2-iy1)*cellsize) + pow2(grid2D(ix2,iy2)-grid2D(ix1,iy1)) );
				const double z1=grid2D(ix1,iy1);
				const double z2=grid2D(ix2,iy2);
477
478
479
				const double tmpx=Optim::pow2((double)(ix2-ix1)*cellsize);
				const double tmpy=Optim::pow2((double)(iy2-iy1)*cellsize);
				const double tmpz=Optim::pow2(z2-z1);
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
				distance += sqrt( tmpx + tmpy + tmpz );
			}
			last_point = ii;
		}
	}

	return distance;
}

/**
* @brief Returns a list of grid points that are on the straight line between two coordinates
* @param point1 first point (ie: origin)
* @param point2 second point (ie: destination)
* @param vec_points vector of points that are in between
*
*/
void DEMObject::getPointsBetween(Coords point1, Coords point2, std::vector<GRID_POINT_2D>& vec_points) {

	if(point1.isSameProj(point2)==false) {
		point1.copyProj(point2);
	}

	if(point1.getEasting() > point2.getEasting()) {
		//we want xcoord1<xcoord2, so we swap the two points
		const Coords tmp = point1;
		point1 = point2;
		point2 = tmp;
	}

	//extension of the line segment (pts1, pts2) along the X axis
	const int ix1 = (int)floor( (point1.getEasting() - llcorner.getEasting())/cellsize );
	const int iy1 = (int)floor( (point1.getNorthing() - llcorner.getNorthing())/cellsize );
	const int ix2 = (int)floor( (point2.getEasting() - llcorner.getEasting())/cellsize );
	const int iy2 = (int)floor( (point2.getNorthing() - llcorner.getNorthing())/cellsize );

	if(ix1==ix2) {
		//special case of vertical alignement
517
		for(int iy=min(iy1,iy2); iy<=max(iy1,iy2); iy++) {
518
519
520
521
522
523
524
525
526
527
528
529
530
531
			GRID_POINT_2D pts;
			pts.ix = ix1;
			pts.iy = iy;
			vec_points.push_back(pts);
		}
	} else {
		//normal case
		//equation of the line between the two points
		const double a = ((double)(iy2-iy1)) / ((double)(ix2-ix1));
		const double b = (double)iy1 - a * (double)ix1;

		for(int ix=ix1; ix<=ix2; ix++) {
			//extension of the line segment (ix, ix+1) along the Y axis
			int y1 = (int)floor( a*(double)ix+b );
532
			//const int y2 = min( (int)floor( a*((double)ix+1)+b ) , iy2);
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
			int y2 = (int)floor( a*((double)ix+1)+b );
			if(ix==ix2 && y1==iy2) {
				//we don't want to overshoot when reaching the target cell
				y2 = y1;
			}

			if(y1>y2) {
				//we want y1<y2, so we swap the two coordinates
				const int ytemp=y1;
				y1=y2; y2=ytemp;
			}

			for(int iy=y1; iy<=y2; iy++) {
				GRID_POINT_2D pts;
				pts.ix = ix;
				pts.iy = iy;
				//make sure we only return points within the dem
				if(ix>0 && ix<(signed)ncols && iy>0 && iy<(signed)nrows) {
					vec_points.push_back(pts);
				}
			}
		}
	}
}

558
559
560
561
562
563
564
/**
* @brief Returns a list of grid points that are on the straight line between two coordinates
* @param point the origin point
* @param bearing direction given by a compass bearing
* @param vec_points vector of points that are between point and the edge of the dem following direction given by bearing
*
*/
565
566
void DEMObject::getPointsBetween(const Coords& point, const double& bearing, std::vector<GRID_POINT_2D>& vec_points) {
	//equation of the line between for a point (x0,y0) and a bearing
567
568
	const double x0 = (point.getEasting() - llcorner.getEasting())/cellsize;
	const double y0 = (point.getNorthing() - llcorner.getNorthing())/cellsize;
569
570
	const double bear=fmod(bearing+360., 360.); //this should not be needed, but as safety...
	const double a = tan( IOUtils::bearing_to_angle(bear) ); //to get trigonometric angle
571
	const double b = y0 - a * x0;
572

573
574
575
	//looking which point is on the limit of the grid and not outside
	Coords pointlim;
	pointlim.copyProj(llcorner); //we use the same projection parameters as the DEM
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599

	//define the boundaries according to the quadrant we are in
	double xlim, ylim;
	if(bear>=0. && bear<90.) {
		xlim = (double)(ncols-1);
		ylim = (double)(nrows-1);
	} else if (bear>=90. && bear<180.) {
		xlim = (double)(ncols-1);
		ylim = 0.;
	} else if (bear>=180. && bear<270.) {
		xlim = 0.;
		ylim = 0.;
	} else {
		xlim = 0.;
		ylim = (double)(nrows-1);
	}

	//calculate the two possible intersections between the bearing line and the boundaries
	const double y2 = a * xlim + b;
	const double x2 = (ylim - b) / (a + 1e-12);

	//Find out which point is the first intersect and take it as our destination point
	if(bear>=90. && bear<270.) {
		if (y2 >= ylim)
600
601
602
        		pointlim.setXY((xlim*cellsize)+llcorner.getEasting(),(y2*cellsize)+llcorner.getNorthing() , IOUtils::nodata);
		else
        		pointlim.setXY((x2*cellsize)+llcorner.getEasting(),(ylim*cellsize)+llcorner.getNorthing() , IOUtils::nodata);
603
	} else {
604
605
606
607
608
		if (y2 <= ylim)
        		pointlim.setXY((xlim*cellsize)+llcorner.getEasting(),(y2*cellsize)+llcorner.getNorthing() , IOUtils::nodata);
		else
        		pointlim.setXY((x2*cellsize)+llcorner.getEasting(),(ylim*cellsize)+llcorner.getNorthing() , IOUtils::nodata);
	}
609

610
	if(gridify(pointlim)==false) {
611
		std::ostringstream tmp;
612
613
		tmp << "[E] Wrong destination point calculated for bearing " << bearing;
		throw InvalidArgumentException(tmp.str(), AT);
614
615
	}

616
617
	getPointsBetween(point, pointlim, vec_points);
	//HACK BUG : for bearing=160 -> both start and end points are missing from the list!!
618
619
620
621
622
623
624
625
626
627
628
}

/**
* @brief Returns the horizon from a given point looking toward a given bearing
* @param point the origin point
* @param bearing direction given by a compass bearing
* @return angle above the horizontal (in deg)
*
*/
double DEMObject::getHorizon(const Coords& point, const double& bearing) {

629
	std::vector<Grid2DObject::GRID_POINT_2D> vec_points;
630
631
	getPointsBetween(point, bearing, vec_points);

632
633
634
635
	//Starting point
	const int ix0 = (int)point.getGridI();
	const int iy0 = (int)point.getGridJ();
	const double height0 = grid2D(ix0,iy0);
636

637
	//going through every point and looking for the highest tangent (which is also the highest angle)
638
	double max_tangent = 0.;
Mathias Bavay's avatar
Mathias Bavay committed
639
	for (size_t ii=0; ii < vec_points.size(); ii++) {
640
641
642
643
644
645
646
647
648
		const int ix = (int)vec_points[ii].ix;
		const int iy = (int)vec_points[ii].iy;
		const double delta_height = grid2D(ix, iy) - height0;
		const double x_distance = (double)(ix - ix0) * cellsize;
		const double y_distance = (double)(iy - iy0) * cellsize;
		const double distance = sqrt(x_distance * x_distance + y_distance * y_distance);
		const double tangent = (delta_height / distance);

		if(tangent > max_tangent) max_tangent = tangent;
649
650
	}

651
	//returning the angle matching the highest tangent
652
	return ( atan(max_tangent)*Cst::to_deg );
653
654
655
656
657
658
659
660
661
}

/**
* @brief Returns the horizon from a given point looking 360 degrees around by increments
* @param point the origin point
* @param increment to the bearing between two angles
* @param horizon vector of heights above a given angle
*
*/
662
663
664
665
666
667
void DEMObject::getHorizon(const Coords& point, const double& increment, std::vector<double>& horizon)
{
	for(double bearing=0.0; bearing <360.; bearing += increment) {
		const double alpha = getHorizon(point, bearing * Cst::PI/180.);
		horizon.push_back(alpha);
	}
668
669
}

670
671
672
void DEMObject::CalculateAziSlopeCurve(slope_type algorithm) {
//This computes the slope and the aspect at a given cell as well as the x and y components of the normal vector
	double A[4][4]; //table to store neigbouring heights: 3x3 matrix but we want to start at [1][1]
673
	                //we use matrix notation: A[y][x]
674
675
676
677
678
679
	if(algorithm==DFLT) {
		algorithm = dflt_algorithm;
	}

	slope_failures = curvature_failures = 0;
	if(algorithm==HICK) {
680
		CalculateSlope = &DEMObject::CalculateHick;
681
	} else if(algorithm==HORN) {
682
		CalculateSlope = &DEMObject::CalculateHorn;
683
	} else if(algorithm==CORR) {
684
		CalculateSlope = &DEMObject::CalculateCorripio;
685
	} else if(algorithm==FLEM) {
686
687
688
689
690
691
692
693
		CalculateSlope = &DEMObject::CalculateFleming;
	} else if(algorithm==D8) {
		CalculateSlope = &DEMObject::CalculateHick;
	} else {
		throw InvalidArgumentException("Chosen slope algorithm not available", AT);
	}

	//Now, calculate the parameters using the previously defined function pointer
Mathias Bavay's avatar
Mathias Bavay committed
694
695
	for ( size_t j = 0; j < nrows; j++ ) {
		for ( size_t i = 0; i < ncols; i++ ) {
696
697
			if( grid2D(i,j) == IOUtils::nodata ) {
				if(update_flag&SLOPE) {
698
					slope(i,j) = azi(i,j) = IOUtils::nodata;
699
700
				}
				if(update_flag&CURVATURE) {
701
					curvature(i,j) = IOUtils::nodata;
702
703
				}
				if(update_flag&NORMAL) {
704
					Nx(i,j) = Ny(i,j) = Nz(i,j) = IOUtils::nodata;
705
706
707
				}
			} else {
				getNeighbours(i, j, A);
708
				double new_slope, new_Nx, new_Ny, new_Nz;
709
				(this->*CalculateSlope)(A, new_slope, new_Nx, new_Ny, new_Nz);
710
711
				const double new_azi = CalculateAspect(new_Nx, new_Ny, new_Nz, new_slope);
				const double new_curvature = getCurvature(A);
712
				if(update_flag&SLOPE) {
713
714
					slope(i,j) = new_slope;
					azi(i,j) = new_azi;
715
716
				}
				if(update_flag&CURVATURE) {
717
					curvature(i,j) = new_curvature;
718
719
				}
				if(update_flag&NORMAL) {
720
721
722
					Nx(i,j) = new_Nx;
					Ny(i,j) = new_Ny;
					Nz(i,j) = new_Nz;
723
724
725
				}
			}
		}
726
727
728
	}

	if((update_flag&SLOPE) && (algorithm==D8)) { //extra processing required: discretization
Mathias Bavay's avatar
Mathias Bavay committed
729
730
		for ( size_t j = 0; j < nrows; j++ ) {
			for ( size_t i = 0; i < ncols; i++ ) {
731
732
733
734
735
736
737
738
739
740
741
742
					//TODO: process flats by an extra algorithm
					if(azi(i,j)!=IOUtils::nodata)
						azi(i,j) = fmod(floor( (azi(i,j)+22.5)/45. )*45., 360.);
					if(slope(i,j)!=IOUtils::nodata)
						slope(i,j) = floor( slope(i,j)+0.5 );
			}
		}
	}

	//Inform the user is some points have unexpectidly not been computed
	//(ie: there was an altitude but some parameters could not be computed)
	if(slope_failures>0 || curvature_failures>0) {
743
		cerr << "[W] DEMObject: " << slope_failures << " point(s) have an elevation but no slope, " << curvature_failures << " point(s) have an elevation but no curvature." << std::endl;
744
745
746
747
	}

} // end of CalculateAziSlope

748
double DEMObject::CalculateAspect(const double& o_Nx, const double& o_Ny, const double& o_Nz, const double& o_slope, const double no_slope) {
749
750
751
752
//Calculates the aspect at a given point knowing its normal vector and slope
//(direction of the normal pointing out of the surface, clockwise from north)
//This azimuth calculation is similar to Hodgson (1998)
//local_nodata is the value that we want to give to the aspect of points that don't have a slope
753
//The value is a bearing (ie: deg, clockwise, 0=North)
754

755
	if(o_Nx==IOUtils::nodata || o_Ny==IOUtils::nodata || o_Nz==IOUtils::nodata || o_slope==IOUtils::nodata) {
756
757
758
		return IOUtils::nodata;
	}

759
760
761
	if ( o_slope > 0. ) { //there is some slope
		if ( o_Nx == 0. ) { //no E-W slope, so it is purely N-S
			if ( o_Ny < 0. ) {
762
				return(180.); // south facing
763
			} else {
764
				return (0.); // north facing
765
766
			}
		} else { //there is a E-W slope
767
768
			if ( o_Nx > 0. ) {
				return (90. - atan(o_Ny/o_Nx)*Cst::to_deg);
769
			} else {
770
				return (270. - atan(o_Ny/o_Nx)*Cst::to_deg);
771
772
773
774
775
776
777
778
			}
		}
	} else { // if slope = 0
		return (no_slope);          // undefined or plain surface
	}
}


779
void DEMObject::CalculateHick(double A[4][4], double& o_slope, double& o_Nx, double& o_Ny, double& o_Nz) {
780
781
782
783
784
785
//This calculates the surface normal vector using the steepest slope method (Dunn and Hickey, 1998):
//the steepest slope found in the eight cells surrounding (i,j) is given to be the slope in (i,j)
//Beware, sudden steps could happen
	const double smax = steepestGradient(A); //steepest local gradient

	if(smax==IOUtils::nodata) {
786
787
788
789
		o_slope = IOUtils::nodata;
		o_Nx = IOUtils::nodata;
		o_Ny = IOUtils::nodata;
		o_Nz = IOUtils::nodata;
790
791
		slope_failures++;
	} else {
792
		o_slope = atan(smax)*Cst::to_deg;
793
794
795
796
797
798

		//Nx and Ny: x and y components of the normal pointing OUT of the surface
		if ( smax > 0. ) { //ie: there is some slope
			double dx_sum, dy_sum;
			surfaceGradient(dx_sum, dy_sum, A);
			if(dx_sum==IOUtils::nodata || dy_sum==IOUtils::nodata) {
799
800
801
				o_Nx = IOUtils::nodata;
				o_Ny = IOUtils::nodata;
				o_Nz = IOUtils::nodata;
802
803
				slope_failures++;
			} else {
804
805
806
				o_Nx = -1.0 * dx_sum / (2. * cellsize);	//Nx=-dz/dx
				o_Ny = -1.0 * dy_sum / (2. * cellsize);	//Ny=-dz/dy
				o_Nz = 1.;				//Nz=1 (normalized by definition of Nx and Ny)
807
808
			}
		} else { //ie: there is no slope
809
810
811
			o_Nx = 0.;
			o_Ny = 0.;
			o_Nz = 1.;
812
813
814
815
		}
	}
}

816
void DEMObject::CalculateFleming(double A[4][4], double& o_slope, double& o_Nx, double& o_Ny, double& o_Nz) {
817
818
//This calculates the surface normal vector using method by Fleming and Hoffer (1979)
	if(A[2][1]!=IOUtils::nodata && A[2][3]!=IOUtils::nodata && A[3][2]!=IOUtils::nodata && A[1][2]!=IOUtils::nodata) {
819
820
821
822
		o_Nx = 0.5 * (A[2][1] - A[2][3]) / cellsize;
		o_Ny = 0.5 * (A[3][2] - A[1][2]) / cellsize;
		o_Nz = 1.;
		o_slope = atan( sqrt(o_Nx*o_Nx+o_Ny*o_Ny) ) * Cst::to_deg;
823
	} else {
824
		CalculateHick(A, o_slope, o_Nx, o_Ny, o_Nz);
825
826
827
	}
}

828
void DEMObject::CalculateHorn(double A[4][4], double& o_slope, double& o_Nx, double& o_Ny, double& o_Nz) {
829
830
831
832
833
//This calculates the slope using the two eight neighbors method given in Horn (1981)
//This is also the algorithm used by ArcGIS
	if ( A[1][1]!=IOUtils::nodata && A[1][2]!=IOUtils::nodata && A[1][3]!=IOUtils::nodata &&
	     A[2][1]!=IOUtils::nodata && A[2][2]!=IOUtils::nodata && A[2][3]!=IOUtils::nodata &&
	     A[3][1]!=IOUtils::nodata && A[3][2]!=IOUtils::nodata && A[3][3]!=IOUtils::nodata) {
834
835
836
		o_Nx = ((A[3][3]+2.*A[2][3]+A[1][3]) - (A[3][1]+2.*A[2][1]+A[1][1])) / (8.*cellsize);
		o_Ny = ((A[1][3]+2.*A[1][2]+A[1][1]) - (A[3][3]+2.*A[3][2]+A[3][1])) / (8.*cellsize);
		o_Nz = 1.;
837
838
839

		//There is no difference between slope = acos(n_z/|n|) and slope = atan(sqrt(sx*sx+sy*sy))
		//slope = acos( (Nz / sqrt( Nx*Nx + Ny*Ny + Nz*Nz )) );
840
		o_slope = atan( sqrt(o_Nx*o_Nx+o_Ny*o_Ny) ) * Cst::to_deg;
841
842
	} else {
		//steepest slope method (Dunn and Hickey, 1998)
843
		CalculateHick(A, o_slope, o_Nx, o_Ny, o_Nz);
844
845
846
	}
}

847
void DEMObject::CalculateCorripio(double A[4][4], double& o_slope, double& o_Nx, double& o_Ny, double& o_Nz) {
848
849
850
851
852
//This calculates the surface normal vector using the two triangle method given in Corripio (2003) but cell centered instead of node centered (ie using a 3x3 grid instead of 2x2)
	if ( A[1][1]!=IOUtils::nodata && A[1][3]!=IOUtils::nodata && A[3][1]!=IOUtils::nodata && A[3][3]!=IOUtils::nodata) {
		// See Corripio (2003), knowing that here we normalize the result (divided by Nz=cellsize*cellsize) and that we are cell centered instead of node centered
		o_Nx = (A[3][1] + A[1][1] - A[3][3] - A[1][3]) / (2.*2.*cellsize);
		o_Ny = (A[3][1] - A[1][1] + A[3][3] - A[1][3]) / (2.*2.*cellsize);
853
		o_Nz = 1.;
854
855
		//There is no difference between slope = acos(n_z/|n|) and slope = atan(sqrt(sx*sx+sy*sy))
		//slope = acos( (Nz / sqrt( Nx*Nx + Ny*Ny + Nz*Nz )) );
856
		o_slope = atan( sqrt(o_Nx*o_Nx+o_Ny*o_Ny) ) * Cst::to_deg;
857
858
	} else {
		//steepest slope method (Dunn and Hickey, 1998)
859
		CalculateHick(A, o_slope, o_Nx, o_Ny, o_Nz);
860
861
862
863
864
865
866
867
868
869
870
871
872
	}
}

double DEMObject::getCurvature(double A[4][4]) {
//This methode computes the curvature of a specific cell
	if(A[2][2]!=IOUtils::nodata) {
		const double Zwe   = avgHeight(A[2][1], A[2][2], A[2][3]);
		const double Zsn   = avgHeight(A[1][2], A[2][2], A[3][2]);
		const double Zswne = avgHeight(A[3][1], A[2][2], A[1][3]);
		const double Znwse = avgHeight(A[1][1], A[2][2], A[3][3]);

		const double sqrt2 = sqrt(2.);
		double sum=0.;
Mathias Bavay's avatar
Mathias Bavay committed
873
		size_t count=0;
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891

		if(Zwe!=IOUtils::nodata) {
			sum += 0.5*(A[2][2]-Zwe);
			count++;
		}
		if(Zsn!=IOUtils::nodata) {
			sum += 0.5*(A[2][2]-Zsn);
			count++;
		}
		if(Zswne!=IOUtils::nodata) {
			sum += 0.5*(A[2][2]-Zswne)/sqrt2;
			count++;
		}
		if(Znwse!=IOUtils::nodata) {
			sum += 0.5*(A[2][2]-Znwse)/sqrt2;
			count++;
		}

Mathias Bavay's avatar
Mathias Bavay committed
892
		if(count != 0.) return 1./(double)count * sum;
893
894
895
896
897
898
899
900
901
902
903
904
	}
	curvature_failures++;
	return IOUtils::nodata;
}

double DEMObject::steepestGradient(double A[4][4]) {
//best effort to calculate the local steepest gradient
	double smax=-1.;		//maximum slope of all neighboring slopes
	const double sqrt2=sqrt(2.);	//the weight of the 4 corner cells is increased by sqrt(2)

	if(A[2][2]!=IOUtils::nodata) {
		if(A[1][1]!=IOUtils::nodata)
905
			smax = max( smax, fabs(A[2][2] - A[1][1])/(cellsize*sqrt2) );
906
		if(A[1][2]!=IOUtils::nodata)
907
			smax = max( smax, fabs(A[2][2] - A[1][2])/(cellsize) );
908
		if(A[1][3]!=IOUtils::nodata)
909
			smax = max( smax, fabs(A[2][2] - A[1][3])/(cellsize*sqrt2) );
910
		if(A[2][1]!=IOUtils::nodata)
911
			smax = max( smax, fabs(A[2][2] - A[2][1])/(cellsize) );
912
		if(A[2][3]!=IOUtils::nodata)
913
			smax = max( smax, fabs(A[2][2] - A[2][3])/(cellsize) );
914
		if(A[3][1]!=IOUtils::nodata)
915
			smax = max( smax, fabs(A[2][2] - A[3][1])/(cellsize*sqrt2) );
916
		if(A[3][2]!=IOUtils::nodata)
917
			smax = max( smax, fabs(A[2][2] - A[3][2])/(cellsize) );
918
		if(A[3][3]!=IOUtils::nodata)
919
			smax = max( smax, fabs(A[2][2] - A[3][3])/(cellsize*sqrt2) );
920
921
922
923
924
925
926
927
928
929
	}

	if(smax<0.)
		return IOUtils::nodata;
	return smax;
}

double DEMObject::lineGradient(const double& A1, const double& A2, const double& A3) {
//best effort to calculate the local gradient
	if(A3!=IOUtils::nodata && A1!=IOUtils::nodata) {
930
		return A3 - A1;
931
932
	} else {
		if(A2!=IOUtils::nodata) {
933
			if(A3!=IOUtils::nodata)
934
				return (A3 - A2)*2.;
935
			if(A1!=IOUtils::nodata)
936
				return (A2 - A1)*2.;
937
938
939
		}
	}

940
	return IOUtils::nodata;
941
942
943
944
945
}

double DEMObject::fillMissingGradient(const double& delta1, const double& delta2) {
//If a gradient could not be computed, try to fill it with some neighboring value
	if(delta1!=IOUtils::nodata && delta2!=IOUtils::nodata) {
946
		return 0.5*(delta1+delta2);
947
	} else {
948
949
		if(delta1!=IOUtils::nodata) return delta1;
		if(delta2!=IOUtils::nodata) return delta2;
950
951
	}

952
	return IOUtils::nodata;
953
954
955
956
}

void DEMObject::surfaceGradient(double& dx_sum, double& dy_sum, double A[4][4]) {
//Compute the gradient for a given cell (i,j) accross its eight surrounding cells (Horn, 1981)
957
958
959
	double dx1 = lineGradient(A[3][1], A[3][2], A[3][3]);
	double dx2 = lineGradient(A[2][1], A[2][2], A[2][3]);
	double dx3 = lineGradient(A[1][1], A[1][2], A[1][3]);
960

961
962
963
	double dy1 = lineGradient(A[3][1], A[2][1], A[1][1]);
	double dy2 = lineGradient(A[3][2], A[2][2], A[1][2]);
	double dy3 = lineGradient(A[3][3], A[2][3], A[1][3]);
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

	//now trying to fill whatever could not be filled...
	if(dx1==IOUtils::nodata) dx1 = fillMissingGradient(dx2, dx3);
	if(dx2==IOUtils::nodata) dx2 = fillMissingGradient(dx1, dx3);
	if(dx3==IOUtils::nodata) dx3 = fillMissingGradient(dx1, dx2);
	if(dy1==IOUtils::nodata) dy1 = fillMissingGradient(dy2, dy3);
	if(dy2==IOUtils::nodata) dy2 = fillMissingGradient(dy1, dy3);
	if(dy3==IOUtils::nodata) dy3 = fillMissingGradient(dy1, dy2);

	if(dx1!=IOUtils::nodata && dy1!=IOUtils::nodata) {
		// principal axis twice to emphasize height difference in that direction
		dx_sum = (dx1 + 2.*dx2 + dx3) * 0.25;
		dy_sum = (dy1 + 2.*dy2 + dy3) * 0.25;
	} else {
		//if dx1==nodata, this also means that dx2==nodata and dx3==nodata
		//(otherwise, dx1 would have received a copy of either dx2 or dx3)
		dx_sum = IOUtils::nodata;
		dy_sum = IOUtils::nodata;
	}
}

double DEMObject::avgHeight(const double& z1, const double &z2, const double& z3) {
//this safely computes the average height accross a vector

	if(z1!=IOUtils::nodata && z3!=IOUtils::nodata) {
		return 0.5*(z1+z3);
	}
	if(z1!=IOUtils::nodata && z2!=IOUtils::nodata) {
		return 0.5*(z1+z2);
	}
	if(z3!=IOUtils::nodata && z2!=IOUtils::nodata) {
		return 0.5*(z3+z2);
	}

	return IOUtils::nodata;
}

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