WSL/SLF GitLab Repository

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

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

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <meteoio/DEMObject.h>
19
#include <limits.h>
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

/**
* @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
* @param _algorithm specify the default algorithm to use for slope computation (default=DFLT)
*/
DEMObject::DEMObject(const slope_type& _algorithm) : Grid2DObject(), slope(), azi(), curvature(), Nx(), Ny(), Nz()
{
	min_altitude = min_slope = min_curvature = std::numeric_limits<double>::max();
	max_altitude = max_slope = max_curvature = -std::numeric_limits<double>::max();
	slope_failures = curvature_failures = 0;
40
	update_flag = INT_MAX;
41
42
43
44
45
46
47
48
49
50
51
52
	setDefaultAlgorithm(_algorithm);
}

/**
* @brief Constructor that sets variables.
* @param _ncols (unsigned int) number of colums in the grid2D
* @param _nrows (unsigned int) number of rows in the grid2D
* @param _cellsize (double) value for cellsize in grid2D
* @param _llcorner lower lower corner point
* @param _algorithm specify the default algorithm to use for slope computation (default=DFLT)
*/
DEMObject::DEMObject(const unsigned int& _ncols, const unsigned int& _nrows,
53
                     const double& _cellsize, const Coords& _llcorner, const slope_type& _algorithm)
54
55
56
57
58
59
	: Grid2DObject(_ncols, _nrows, _cellsize, _llcorner),
	  slope(), azi(), curvature(), Nx(), Ny(), Nz()
{
	min_altitude = min_slope = min_curvature = std::numeric_limits<double>::max();
	max_altitude = max_slope = max_curvature = -std::numeric_limits<double>::max();
	slope_failures = curvature_failures = 0;
60
	update_flag = INT_MAX;
61
62
63
64
65
66
67
68
69
70
71
72
73
74
	setDefaultAlgorithm(_algorithm);
}

/**
* @brief Constructor that sets variables.
* @param _ncols (unsigned int) number of colums in the grid2D
* @param _nrows (unsigned int) number of rows in the grid2D
* @param _cellsize (double) value for cellsize in grid2D
* @param _llcorner lower lower corner point
* @param _altitude (Array2D\<double\>&) grid2D of elevations
* @param _update (bool) also update slope/normals/curvatures and their min/max? (default=true)
* @param _algorithm specify the default algorithm to use for slope computation (default=DFLT)
*/
DEMObject::DEMObject(const unsigned int& _ncols, const unsigned int& _nrows,
75
76
                     const double& _cellsize, const Coords& _llcorner, const Array2D<double>& _altitude,
                     const bool& _update, const slope_type& _algorithm)
77
78
79
80
	: Grid2DObject(_ncols, _nrows, _cellsize, _llcorner, _altitude),
	  slope(), azi(), curvature(), Nx(), Ny(), Nz()
{
	slope_failures = curvature_failures = 0;
81
	update_flag = INT_MAX;
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
	setDefaultAlgorithm(_algorithm);
	if(_update==false) {
		updateAllMinMax();
	} else {
		update(_algorithm);
	}
}

/**
* @brief Constructor that sets variables from a Grid2DObject
* @param _dem (Grid2DObject&) grid contained in a Grid2DObject
* @param _update (bool) also update slope/normals/curvatures and their min/max? (default=true)
* @param _algorithm specify the default algorithm to use for slope computation (default=DFLT)
*/
DEMObject::DEMObject(const Grid2DObject& _dem, const bool& _update, const slope_type& _algorithm)
  : Grid2DObject(_dem.ncols, _dem.nrows, _dem.cellsize, _dem.llcorner, _dem.grid2D),
    slope(), azi(), curvature(), Nx(), Ny(), Nz()
{
	slope_failures = curvature_failures = 0;
101
	update_flag = INT_MAX;
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
	setDefaultAlgorithm(_algorithm);
	if(_update==false) {
		updateAllMinMax();
	} else {
		update(_algorithm);
	}
}

/**
* @brief Constructor that sets variables from a subset of another DEMObject, 
* given an origin (X,Y) (first index being 0) and a number of columns and rows
* @param _dem (DEMObject&) dem contained in a DEMDObject
* @param _nx (unsigned int&) X coordinate of the new origin
* @param _ny (unsigned int&) Y coordinate of the new origin
* @param _ncols (unsigned int&) number of columns for the subset dem
* @param _nrows (unsigned int&) number of rows for the subset dem
* @param _update (bool) also update slope/normals/curvatures and their min/max? (default=true)
* @param _algorithm specify the default algorithm to use for slope computation (default=DFLT)
*/
DEMObject::DEMObject(const DEMObject& _dem, const unsigned int& _nx, const unsigned int& _ny, 
122
123
124
125
                     const unsigned int& _ncols, const unsigned int& _nrows,
                     const bool& _update, const slope_type& _algorithm)
                     : Grid2DObject(_dem, _nx,_ny, _ncols,_nrows),
                       slope(), azi(), curvature(), Nx(), Ny(), Nz()
126
127
128
129
{
	if ((_ncols==0) || (_nrows==0)) {
		throw InvalidArgumentException("requesting a subset of 0 columns or rows for DEMObject", AT);
	}
130
131
	
	//handling of the update properties
132
	slope_failures = curvature_failures = 0;
133
	update_flag = _dem.getUpdatePpt();
134
	setDefaultAlgorithm(_algorithm);
135
136
137
	if(_update==true) {
		//if the object is in automatic update, then we only process the arrays according to
		//the update_flag
138
		update(_algorithm);
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
	} else {
		//if the object is NOT in automatic update, we manually copy all non-empty arrays
		//from the original set
		unsigned int nx, ny;
		
		_dem.slope.size(nx, ny);
		if(nx>0 && ny>0) {
			slope.subset(_dem.slope,_nx,_ny, _ncols,_nrows);
		}
		_dem.azi.size(nx, ny);
		if(nx>0 && ny>0) {
			azi.subset(_dem.azi,_nx,_ny, _ncols,_nrows);
		}
		_dem.curvature.size(nx, ny);
		if(nx>0 && ny>0) {
			curvature.subset(_dem.curvature,_nx,_ny, _ncols,_nrows);
		}
		_dem.Nx.size(nx, ny);
		if(nx>0 && ny>0) {
			Nx.subset(_dem.Nx,_nx,_ny, _ncols,_nrows);
		}
		_dem.Ny.size(nx, ny);
		if(nx>0 && ny>0) {
			Ny.subset(_dem.Ny,_nx,_ny, _ncols,_nrows);
		}
		_dem.Nz.size(nx, ny);
		if(nx>0 && ny>0) {
			Nz.subset(_dem.Nz,_nx,_ny, _ncols,_nrows);
		}

		updateAllMinMax();
170
171
172
	}
}

173
174
175
176
177
178
179
180
181
182
183
184
185
186
/**
* @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
*/
187
int DEMObject::getUpdatePpt() const {
188
189
190
	return update_flag;
}

191
192
193
194
195
196
197
198
199
200
201
/**
* @brief Force the computation of the local slope, azimuth, normal vector and curvature.
* It has to be called manually since it can require some time to compute. Without this call, 
* the above mentionned parameters are NOT up to date.
* @param algorithm (slope_type&) algorithm to use for computing slope, azimuth and normals
*/
void DEMObject::update(const slope_type& algorithm) {
//This method recomputes the attributes that are not read as parameters 
//(such as slope, azimuth, normal vector)

	// Creating tables
202
203
204
205
206
207
208
209
210
211
212
213
	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);
	}
214
215
216
217
218
219
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275

	CalculateAziSlopeCurve(algorithm);
	updateAllMinMax();
}

/**
* @brief Force the computation of the local slope, azimuth, normal vector and curvature.
* It has to be called manually since it can require some time to compute. Without this call, 
* the above mentionned parameters are NOT up to date.
* @param algorithm (const string&) algorithm to use for computing slope, azimuth and normals
* 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.
* 
* The azimuth is always computed using the Hodgson (1998) algorithm.
*/
void DEMObject::update(const std::string& algorithm) {
//This method recomputes the attributes that are not read as parameters 
//(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);
	}
	
	update(type);
}

/**
* @brief Sets the default slope calculation algorithm
* @param _algorithm specify the default algorithm to use for slope computation
*/
void DEMObject::setDefaultAlgorithm(const slope_type& _algorithm) {
//This method MUST be called by each constructor!
	if(_algorithm==DFLT) {
		dflt_algorithm = CORR;
	} else {
		dflt_algorithm = _algorithm;
	}
}

/**
* @brief Recomputes the min/max of altitude, slope and curvature
* It return +/- std::numeric_limits\<double\>::max() for a given parameter if its grid was empty/undefined
*/
void DEMObject::updateAllMinMax() {
//updates the min/max parameters of all 2D tables
276
277
278
279
280
281
282
283
284
	if(update_flag&SLOPE) {
		min_slope = slope.getMin(IOUtils::PARSE_NODATA);
		max_slope = slope.getMax(IOUtils::PARSE_NODATA);
	}
	if(update_flag&CURVATURE) {
		min_curvature = curvature.getMin(IOUtils::PARSE_NODATA);
		max_curvature = curvature.getMax(IOUtils::PARSE_NODATA);
	}

285
286
287
288
289
290
291
292
293
294
295
296
	min_altitude = grid2D.getMin(IOUtils::PARSE_NODATA);
	max_altitude = grid2D.getMax(IOUtils::PARSE_NODATA);
}

/**
* @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;

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
	if(update_flag&SLOPE) {
		for ( unsigned int i = 0; i < ncols; i++ ) {
			for ( unsigned int j = 0; j < nrows; j++ ) {
				if((slope(i,j)==IOUtils::nodata) && (grid2D(i,j)!=IOUtils::nodata)) {
					if(header==true) {
						std::cout << "[i] DEM slope could not be computed at the following points \n";
						std::cout << "[i]\tGrid Point\tElevation\tSlope\n";
						header=false;
					}
					std::cout << "[i]\t(" << i << "," << j << ")" << "\t\t" << grid2D(i,j) << "\t\t" << slope(i,j) << "\n";
				}
			}
		}
	}

	if(update_flag&CURVATURE) {
		for ( unsigned int i = 0; i < ncols; i++ ) {
			for ( unsigned int j = 0; j < nrows; j++ ) {
				if((curvature(i,j)==IOUtils::nodata) && (grid2D(i,j)!=IOUtils::nodata)) {
					if(header==true) {
						std::cout << "[i] DEM curvature could not be computed at the following points \n";
						std::cout << "[i]\tGrid Point\tElevation\tCurvature\n";
						header=false;
					}
					std::cout << "[i]\t(" << i << "," << j << ")" << "\t\t" << grid2D(i,j) << "\t\t" <<  curvature(i,j) << "\n";
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
				}
			}
		}
	}
	if(header==false) {
		std::cout << std::endl;
	}
}

/**
* @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) {
		for ( unsigned int i = 0; i < ncols; i++ ) {
			for ( unsigned int j = 0; j < nrows; j++ ) {
344
345
346
347
348
349
350
351
352
				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;
					}
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
				}
			}
		}
	}
}

/**
* @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)
{
	return sqrt( IOUtils::pow2(xcoord2-xcoord1) + IOUtils::pow2(ycoord2-ycoord1) );
}

/**
* @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(),
			point2.getEasting(), point2.getNorthing() );
}


/**
* @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.;
	unsigned int last_point=0; //point 0 is always the starting point

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

	for(unsigned int ii=1; ii<vec_points.size(); ii++) {
		const int ix1=vec_points[last_point].ix;
		const int iy1=vec_points[last_point].iy;
		const int ix2=vec_points[ii].ix;
		const int iy2=vec_points[ii].iy;

		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);
				const double tmpx=IOUtils::pow2((double)(ix2-ix1)*cellsize);
				const double tmpy=IOUtils::pow2((double)(iy2-iy1)*cellsize);
				const double tmpz=IOUtils::pow2(z2-z1);
				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
		for(int iy=MIN(iy1,iy2); iy<=MAX(iy1,iy2); iy++) {
			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 );
			//const int y2 = MIN( (int)floor( a*((double)ix+1)+b ) , iy2);
			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);
				}
			}
		}
	}
}

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]
503
504
	double _slope, _azi, _curvature;
	double _Nx, _Ny, _Nz;
505
506
507
508
509
510
511

	if(algorithm==DFLT) {
		algorithm = dflt_algorithm;
	}

	slope_failures = curvature_failures = 0;
	if(algorithm==HICK) {
512
		CalculateSlope = &DEMObject::CalculateHick;
513
	} else if(algorithm==HORN) {
514
		CalculateSlope = &DEMObject::CalculateHorn;
515
	} else if(algorithm==CORR) {
516
		CalculateSlope = &DEMObject::CalculateCorripio;
517
	} else if(algorithm==FLEM) {
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
		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
	for ( unsigned int i = 0; i < ncols; i++ ) {
		for ( unsigned int j = 0; j < nrows; j++ ) {
			if( grid2D(i,j) == IOUtils::nodata ) {
				if(update_flag&SLOPE) {
					_slope = _azi = IOUtils::nodata;
				}
				if(update_flag&CURVATURE) {
					_curvature = IOUtils::nodata;
				}
				if(update_flag&NORMAL) {
					_Nx = _Ny = _Nz = IOUtils::nodata;
				}
			} else {
				getNeighbours(i, j, A);
				(this->*CalculateSlope)(A, _slope, _Nx, _Ny, _Nz);
				_azi = CalculateAspect(_Nx, _Ny, _Nz, _slope);
				_curvature = getCurvature(A);
				if(update_flag&SLOPE) {
					slope(i,j) = _slope;
					azi(i,j) = _azi;
				}
				if(update_flag&CURVATURE) {
					curvature(i,j) = _curvature;
				}
				if(update_flag&NORMAL) {
					Nx(i,j) = _Nx;
					Ny(i,j) = _Ny;
					Nz(i,j) = _Nz;
554
555
556
				}
			}
		}
557
558
559
	}

	if((update_flag&SLOPE) && (algorithm==D8)) { //extra processing required: discretization
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
		for ( unsigned int i = 0; i < ncols; i++ ) {
			for ( unsigned int j = 0; j < nrows; j++ ) {
					//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) {
		std::cout << "[W] DEMObject: " << slope_failures << " point(s) have an elevation but no slope, " << curvature_failures << " point(s) have an elevation but no curvature." << std::endl;
	}

} // end of CalculateAziSlope

double DEMObject::CalculateAspect(const double& Nx, const double& Ny, const double& Nz, const double& slope, const double no_slope) {
//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

	if(Nx==IOUtils::nodata || Ny==IOUtils::nodata || Nz==IOUtils::nodata || slope==IOUtils::nodata) {
		return IOUtils::nodata;
	}

	if ( slope > 0. ) { //there is some slope
		if ( Nx == 0. ) { //no E-W slope, so it is purely N-S
			if ( Ny < 0. ) {
				return (M_PI);	  // south facing
			} else {
				return (0.);	  // north facing
			}
		} else { //there is a E-W slope
			const double N_norm = sqrt( Nx*Nx + Ny*Ny + Nz*Nz );
			if ( Nx > 0. ) {
				return (M_PI * 0.5 - atan( (Ny/N_norm) / (Nx/N_norm) ));
			} else {
				return (M_PI * 1.5 - atan( (Ny/N_norm) / (Nx/N_norm) ));
			}
		}
	} else { // if slope = 0
		return (no_slope);          // undefined or plain surface
	}
}


void DEMObject::CalculateHick(double A[4][4], double& slope, double& Nx, double& Ny, double& Nz) {
//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) {
		slope = IOUtils::nodata;
		Nx = IOUtils::nodata;
		Ny = IOUtils::nodata;
		Nz = IOUtils::nodata;
		slope_failures++;
	} else {
		slope = atan( smax );

		//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) {
				Nx = IOUtils::nodata;
				Ny = IOUtils::nodata;
				Nz = IOUtils::nodata;
				slope_failures++;
			} else {
				Nx = -1.0 * dx_sum / (2. * cellsize);	//Nx=-dz/dx
				Ny = -1.0 * dy_sum / (2. * cellsize);	//Ny=-dz/dy
				Nz = 1.;				//Nz=1 (normalized by definition of Nx and Ny)
			}
		} else { //ie: there is no slope
			Nx = 0.;
			Ny = 0.;
			Nz = 1.;
		}
	}
}

void DEMObject::CalculateFleming(double A[4][4], double& slope, double& Nx, double& Ny, double& Nz) {
//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) {
		Nx = 0.5 * (A[2][1] - A[2][3]) / cellsize;
		Ny = 0.5 * (A[3][2] - A[1][2]) / cellsize;
		Nz = 1.;
		slope = atan( sqrt(Nx*Nx+Ny*Ny) );
	} else {
		CalculateHick(A, slope, Nx, Ny, Nz);
	}
}

void DEMObject::CalculateHorn(double A[4][4], double& slope, double& Nx, double& Ny, double& Nz) {
//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) {
		Nx = ((A[3][3]+2.*A[2][3]+A[1][3]) - (A[3][1]+2.*A[2][1]+A[1][1])) / (8.*cellsize);
		Ny = ((A[1][3]+2.*A[1][2]+A[1][1]) - (A[3][3]+2.*A[3][2]+A[3][1])) / (8.*cellsize);
		Nz = 1.;

		//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 )) );
		slope = atan( sqrt(Nx*Nx+Ny*Ny) );
	} else {
		//steepest slope method (Dunn and Hickey, 1998)
		CalculateHick(A, slope, Nx, Ny, Nz);
	}
}

void DEMObject::CalculateCorripio(double A[4][4], double& slope, double& Nx, double& Ny, double& Nz) {
//This calculates the surface normal vector using the two triangle method given in Corripio (2002)
	if ( A[1][2]!=IOUtils::nodata && A[1][3]!=IOUtils::nodata && A[2][2]!=IOUtils::nodata && A[2][3]!=IOUtils::nodata) {
		// See Corripio (2002), knowing that here we normalize the result (divided by Nz=cellsize*cellsize)
		Nx = (0.5 * (A[2][2] - A[2][3] + A[1][2] - A[1][3]) ) / cellsize;
		Ny = (0.5 * (A[2][2] + A[2][3] - A[1][2] - A[1][3]) ) / cellsize;
		Nz = 1.;
		//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 )) );
		slope = atan( sqrt(Nx*Nx+Ny*Ny) );
	} else {
		//steepest slope method (Dunn and Hickey, 1998)
		CalculateHick(A, slope, Nx, Ny, Nz);
	}
}

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.;
		unsigned int count=0;

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

		if(count != 0.) return 1./count * sum;
	}
	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)
			smax = MAX( smax, fabs(A[2][2] - A[1][1])/(cellsize*sqrt2) );
		if(A[1][2]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[1][2])/(cellsize) );
		if(A[1][3]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[1][3])/(cellsize*sqrt2) );
		if(A[2][1]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[2][1])/(cellsize) );
		if(A[2][3]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[2][3])/(cellsize) );
		if(A[3][1]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[3][1])/(cellsize*sqrt2) );
		if(A[3][2]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[3][2])/(cellsize) );
		if(A[3][3]!=IOUtils::nodata)
			smax = MAX( smax, fabs(A[2][2] - A[3][3])/(cellsize*sqrt2) );
	}

	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
	double delta = IOUtils::nodata;

	if(A3!=IOUtils::nodata && A1!=IOUtils::nodata) {
		delta = A3 - A1;
	} else {
		if(A2!=IOUtils::nodata) {
			if(A3!=IOUtils::nodata) 
				delta = (A3 - A2) * 2.;
			if(A1!=IOUtils::nodata) 
				delta = (A2 - A1) * 2.;
		}
	}

	return delta;
}

double DEMObject::fillMissingGradient(const double& delta1, const double& delta2) {
//If a gradient could not be computed, try to fill it with some neighboring value
	double dx = IOUtils::nodata;

	if(delta1!=IOUtils::nodata && delta2!=IOUtils::nodata) {
		dx = 0.5 * (delta1+delta2);
	} else {
		if(delta1!=IOUtils::nodata) dx = delta1;
		if(delta2!=IOUtils::nodata) dx = delta2;
	}

	return dx;
}

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)
	double dx1, dx2, dx3;
	double dy1, dy2, dy3;

	//general calculation
	dx1 = lineGradient(A[3][1], A[3][2], A[3][3]);
	dx2 = lineGradient(A[2][1], A[2][2], A[2][3]);
	dx3 = lineGradient(A[1][1], A[1][2], A[1][3]);

	dy1 = lineGradient(A[3][1], A[2][1], A[1][1]);
	dy2 = lineGradient(A[3][2], A[2][2], A[1][2]);
	dy3 = lineGradient(A[3][3], A[2][3], A[1][3]);

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

void DEMObject::getNeighbours(const unsigned int i, const unsigned int j, double A[4][4]) {
//this fills a 3x3 table containing the neighboring values
		A[1][1] = safeGet(i-1, j+1);
		A[1][2] = safeGet(i, j+1);
		A[1][3] = safeGet(i+1, j+1);
		A[2][1] = safeGet(i-1, j);
		A[2][2] = safeGet(i, j);
		A[2][3] = safeGet(i+1, j);
		A[3][1] = safeGet(i-1, j-1);
		A[3][2] = safeGet(i, j-1);
		A[3][3] = safeGet(i+1, j-1);
}

double DEMObject::safeGet(const int i, const int j)
{//this function would allow reading the value of *any* point, 
//that is, even for coordinates outside of the grid (where it would return nodata)
//this is to make implementing the slope/curvature computation easier for edges, holes, etc

	if(i<0 || i>=(signed)ncols) {
		return IOUtils::nodata;
	}
	if(j<0 || j>=(signed)nrows) {
		return IOUtils::nodata;
	}
	
	return grid2D((unsigned)i, (unsigned)j);
}

} //end namespace

#ifdef _POPC_
#include "marshal_meteoio.h"
using namespace mio; //HACK for POPC
void DEMObject::Serialize(POPBuffer &buf, bool pack)
{
	if (pack)
	{
		buf.Pack(&ncols,1);
		buf.Pack(&nrows,1);
		buf.Pack(&cellsize,1);
		marshal_Coords(buf, llcorner, 0, FLAG_MARSHAL, NULL);
		buf.Pack(&min_altitude,1);
		buf.Pack(&max_altitude,1);
		buf.Pack(&min_slope,1);
		buf.Pack(&max_slope,1);
		buf.Pack(&min_curvature,1);
		buf.Pack(&max_curvature,1);
		buf.Pack(&slope_failures,1);
		buf.Pack(&curvature_failures,1);
890
		buf.Pack(&update_flag,1);
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
		marshal_slope_type(buf, dflt_algorithm, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, grid2D, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, slope, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, azi, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, curvature, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, Nx, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, Ny, 0, FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, Nz, 0, FLAG_MARSHAL, NULL);
	}
	else
	{
		buf.UnPack(&ncols,1);
		buf.UnPack(&nrows,1);
		buf.UnPack(&cellsize,1);
		marshal_Coords(buf, llcorner, 0, !FLAG_MARSHAL, NULL);
		buf.UnPack(&min_altitude,1);
		buf.UnPack(&max_altitude,1);
		buf.UnPack(&min_slope,1);
		buf.UnPack(&max_slope,1);
		buf.UnPack(&min_curvature,1);
		buf.UnPack(&max_curvature,1);
		buf.UnPack(&slope_failures,1);
		buf.UnPack(&curvature_failures,1);
914
		buf.UnPack(&update_flag,1);
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
		grid2D.clear();//if(grid2D!=NULL)delete(grid2D);
		slope.clear();
		azi.clear();
		curvature.clear();
		Nx.clear();
		Ny.clear();
		Nz.clear();
		marshal_slope_type(buf, dflt_algorithm, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, grid2D, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, slope, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, azi, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, curvature, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, Nx, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, Ny, 0, !FLAG_MARSHAL, NULL);
		marshal_DOUBLE2D(buf, Nz, 0, !FLAG_MARSHAL, NULL);
	}
}
#endif

//} //namespace //HACK for POPC