WSL/SLF GitLab Repository

libinterpol2D.cc 26 KB
 Mathias Bavay committed Sep 20, 2013 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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 ``````/***********************************************************************************/ /* 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 . */ #include #include #include #include //for math constants #include //math optimizations using namespace std; namespace mio { const double Interpol2D::wind_ys = 0.58; const double Interpol2D::wind_yc = 0.42; //Usefull functions /** * @brief Computes the horizontal distance between points, given by coordinates in a geographic grid * @param X1 (const double) first point's X coordinate * @param Y1 (const double) first point's Y coordinate * @param X2 (const double) second point's X coordinate * @param Y2 (const double) second point's Y coordinate * @return (double) distance in m */ inline double Interpol2D::HorizontalDistance(const double& X1, const double& Y1, const double& X2, const double& Y2) { //This function computes the horizontaldistance between two points //coordinates are given in a square, metric grid system const double DX=(X1-X2), DY=(Y1-Y2); return sqrt( DX*DX + DY*DY ); } /** * @brief Computes the 1/horizontal distance between points, given by coordinates in a geographic grid * @param X1 (const double) first point's X coordinate * @param Y1 (const double) first point's Y coordinate * @param X2 (const double) second point's X coordinate * @param Y2 (const double) second point's Y coordinate * @return (double) 1/distance in m */ inline double Interpol2D::InvHorizontalDistance(const double& X1, const double& Y1, const double& X2, const double& Y2) { //This function computes 1/horizontaldistance between two points //coordinates are given in a square, metric grid system const double DX=(X1-X2), DY=(Y1-Y2); return Optim::invSqrt( DX*DX + DY*DY ); //we use the optimized approximation for 1/sqrt `````` 62 ``````} `````` Mathias Bavay committed Sep 20, 2013 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 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 `````` /** * @brief Computes the horizontal distance between points, given by their cells indexes * @param X1 (const double) first point's i index * @param Y1 (const double) first point's j index * @param X2 (const double) second point's X coordinate * @param Y2 (const double) second point's Y coordinate * @return (double) distance in m */ inline double Interpol2D::HorizontalDistance(const DEMObject& dem, const int& i, const int& j, const double& X2, const double& Y2) { //This function computes the horizontal distance between two points //coordinates are given in a square, metric grid system //for grid points toward real coordinates const double X1 = (dem.llcorner.getEasting()+i*dem.cellsize); const double Y1 = (dem.llcorner.getNorthing()+j*dem.cellsize); const double DX=(X1-X2), DY=(Y1-Y2); return sqrt( DX*DX + DY*DY ); } /** * @brief Build the list of (distance to grid cell, stations index) ordered by their distance to a grid cell * @param x x coordinate of cell * @param y y coordinate of cell * @param list list of pairs (distance to grid cell, stations index) */ void Interpol2D::getNeighbors(const double& x, const double& y, const std::vector& vecStations, std::vector< std::pair >& list) { list.resize(vecStations.size()); for(size_t i=0; i tmp(d2,i); list[i] = tmp; } sort (list.begin(), list.end()); } //convert a vector of stations into two vectors of eastings and northings void Interpol2D::buildPositionsVectors(const std::vector& vecStations, std::vector& vecEastings, std::vector& vecNorthings) { vecEastings.resize( vecStations.size() ); vecNorthings.resize( vecStations.size() ); for (size_t i=0; i& vecData_in, const std::vector& vecEastings, const std::vector& vecNorthings) { //The value at any given cell is the sum of the weighted contribution from each source const size_t n_stations=vecEastings.size(); double parameter=0., norm=0.; const double scale = 1.e6; for (size_t i=0; i& vecData_in, const std::vector& vecStations_in, const DEMObject& dem, const size_t& nrOfNeighbors, Grid2DObject& grid, double& r2) { unsigned int count=0; double sum=0; grid.set(dem.ncols, dem.nrows, dem.cellsize, dem.llcorner); //run algorithm for (size_t j=0; j0) r2 = sum/(double)count; else r2 = 0.; } //calculate a local pixel for LocalLapseIDW double Interpol2D::LLIDW_pixel(const size_t& i, const size_t& j, const std::vector& vecData_in, const std::vector& vecStations_in, const DEMObject& dem, const size_t& nrOfNeighbors, double& r2) { const double& cell_altitude=dem.grid2D(i,j); if(cell_altitude==IOUtils::nodata) return IOUtils::nodata; std::vector< std::pair > list; std::vector X, Y, coeffs; //fill vectors with appropriate neighbors const double x = dem.llcorner.getEasting()+i*dem.cellsize; const double y = dem.llcorner.getNorthing()+j*dem.cellsize; getNeighbors(x, y, vecStations_in, list); const size_t max_stations = std::min(list.size(), nrOfNeighbors); for(size_t st=0; st0) return (pixel_value/norm); else return IOUtils::nodata; }*/ /** * @brief Grid filling function: * This implementation fills a grid using Inverse Distance Weighting. * for example, the air temperatures measured at several stations would be given as values, the stations positions * as positions and projected to a grid. No elevation detrending is performed, the DEM is only used for checking if a grid point is "nodata". * @param vecData_in input values to use for the IDW * @param vecStations_in position of the "values" (altitude and coordinates) * @param dem array of elevations (dem). This is needed in order to know if a point is "nodata" * @param grid 2D array to fill */ void Interpol2D::IDW(const std::vector& vecData_in, const std::vector& vecStations_in, const DEMObject& dem, Grid2DObject& grid) { grid.set(dem.ncols, dem.nrows, dem.cellsize, dem.llcorner); std::vector vecEastings, vecNorthings; buildPositionsVectors(vecStations_in, vecEastings, vecNorthings); //multiple source stations: simple IDW Krieging const double xllcorner = dem.llcorner.getEasting(); const double yllcorner = dem.llcorner.getNorthing(); const double cellsize = dem.cellsize; for (size_t jj=0; jjsetUpdatePpt((DEMObject::update_type)(DEMObject::SLOPE|DEMObject::CURVATURE)); intern_dem->update(); } const DEMObject *dem = (recomputeDEM)? intern_dem : &i_dem; //This method computes the speed of the wind and returns a table in 2D with this values double speed; // Wind speed (m s-1) double dir; // Wind direction double u; // Zonal component u (m s-1) double v; // Meridional component v (m s-1) double beta; // Terrain slope double azi; // Topographic slope azimuth double curvature; // Topographic curvature double slopeDir; // Slope in the direction of the wind double Ww; // Wind weighting double Od; // Diverting factor const double dem_min_slope=dem->min_slope*Cst::to_rad; const double dem_min_curvature=dem->min_curvature; double dem_range_slope=(dem->max_slope-dem_min_slope)*Cst::to_rad; double dem_range_curvature=(dem->max_curvature-dem_min_curvature); if(dem_range_slope==0.) dem_range_slope = 1.; //to avoid division by zero below if(dem_range_curvature==0.) dem_range_curvature = 1.; //to avoid division by zero below for (size_t j=0;jslope(i, j)*Cst::to_rad; azi = dem->azi(i, j)*Cst::to_rad; curvature = dem->curvature(i, j); if(speed==IOUtils::nodata || dir==IOUtils::nodata || beta==IOUtils::nodata || azi==IOUtils::nodata || curvature==IOUtils::nodata) { VW.grid2D(i, j) = IOUtils::nodata; DW.grid2D(i, j) = IOUtils::nodata; } else { //convert direction to rad dir *= Cst::to_rad; //Speed and direction converted to zonal et meridional //components u = (-1.) * (speed * sin(dir)); v = (-1.) * (speed * cos(dir)); // Converted back to speed and direction speed = sqrt(u*u + v*v); dir = (1.5 * Cst::PI) - atan(v/u); //normalize curvature and beta. //Note: it should be slopeDir instead of beta, but beta is more efficient //to compute (only once for each dem) and it should not be that different... beta = (beta - dem_min_slope)/dem_range_slope - 0.5; curvature = (curvature - dem_min_curvature)/dem_range_curvature - 0.5; // Calculate the slope in the direction of the wind slopeDir = beta * cos(dir - azi); // Calculate the wind weighting factor Ww = 1. + wind_ys * slopeDir + wind_yc * curvature; // Modify the wind direction by a diverting factor Od = -0.5 * slopeDir * sin(2.*(azi - dir)); // Calculate the terrain-modified wind speed VW.grid2D(i, j) = Ww * speed; // Add the diverting factor to the wind direction and convert to degrees DW.grid2D(i, j) = (dir + Od) * Cst::to_deg; if( DW.grid2D(i, j)>360. ) { DW.grid2D(i, j) -= 360.; } } } } if(intern_dem!=NULL) delete (intern_dem); } /** * @brief Distribute precipitation in a way that reflects snow redistribution on the ground, according to (Huss, 2008) * This method modifies the solid precipitation distribution according to the local slope and curvature. See * "Quantitative evaluation of different hydrological modelling approaches in a partly glacierized Swiss watershed", Magnusson et All., Hydrological Processes, 2010, under review. * and * "Modelling runoff from highly glacierized alpine catchments in a changing climate", Huss et All., Hydrological Processes, 22, 3888-3902, 2008. * @param dem array of elevations (dem). The slope must have been updated as it is required for the DEM analysis. * @param ta array of air temperatures used to determine if precipitation is rain or snow * @param grid 2D array of precipitation to fill * @author Florian Kobierska, Jan Magnusson, Rob Spence and Mathias Bavay */ void Interpol2D::CurvatureCorrection(DEMObject& dem, const Grid2DObject& ta, Grid2DObject& grid) { if(!grid.isSameGeolocalization(dem)) { throw IOException("Requested grid does not match the geolocalization of the DEM", AT); } `````` 443 `````` const double dem_max_curvature = dem.max_curvature, dem_range_curvature=(dem.max_curvature-dem.min_curvature); `````` Mathias Bavay committed Sep 20, 2013 444 445 `````` if(dem_range_curvature==0.) return; `````` 446 447 `````` const double orig_mean = grid.grid2D.getMean(); `````` Mathias Bavay committed Sep 20, 2013 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 `````` for (size_t j=0;j273.15) continue; //modify the grid of precipitations only if air temperature is below or at freezing const double slope = dem.slope(i, j); const double curvature = dem.curvature(i, j); if(slope==IOUtils::nodata || curvature==IOUtils::nodata) continue; double& val = grid.grid2D(i, j); if(val!=IOUtils::nodata && dem_range_curvature!=0.) { //cf Huss val *= 0.5-(curvature-dem_max_curvature) / dem_range_curvature; } } } //HACK: correction for precipitation sum over the whole domain //this is a cheap/crappy way of compensating for the spatial redistribution of snow on the slopes const double new_mean = grid.grid2D.getMean(); `````` 466 `````` if(new_mean!=0.) grid.grid2D *= orig_mean/new_mean; `````` Mathias Bavay committed Sep 20, 2013 467 `````` `````` 468 469 470 471 ``````} void Interpol2D::steepestDescentDisplacement(const DEMObject& dem, const Grid2DObject& grid, const size_t& ii, const size_t& jj, short &d_i_dest, short &d_j_dest) { `````` Mathias Bavay committed Sep 20, 2013 472 `````` double max_slope = 0.; `````` 473 474 `````` d_i_dest = 0, d_j_dest = 0; `````` Mathias Bavay committed Sep 20, 2013 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 `````` //loop around all adjacent cells to find the cell with the steepest downhill slope for(short d_i=-1; d_i<=1; d_i++) { for(short d_j=-1; d_j<=1; d_j++) { const double elev_pt1 = dem.grid2D(ii, jj); const double elev_pt2 = dem.grid2D(ii + d_i, jj + d_j); const double precip_1 = grid.grid2D(ii, jj); const double precip_2 = grid.grid2D(ii + d_i, jj + d_j); const double height_ratio = (elev_pt1+precip_1) / (elev_pt2+precip_2); const double new_slope = dem.slope(ii + d_i, jj + d_j); if ((new_slope>max_slope) && (height_ratio>1.)){ max_slope = new_slope; d_i_dest = d_i; d_j_dest = d_j; } } } `````` 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 517 518 519 520 ``````} double Interpol2D::depositAroundCell(const DEMObject& dem, const size_t& ii, const size_t& jj, const double& precip, Grid2DObject &grid) { //else add precip to the cell and remove the same amount from the precip variable grid.grid2D(ii, jj) += precip; double distributed_precip = precip; for(short d_i=-1;d_i<=1;d_i++){ for(short d_j=-1;d_j<=1;d_j++){ const double elev_pt1 = dem.grid2D(ii, jj); const double elev_pt2 = dem.grid2D(ii + d_i, jj + d_j); const double precip_1 = grid.grid2D(ii, jj); const double precip_2 = grid.grid2D(ii + d_i, jj + d_j); const double height_ratio = (elev_pt1+precip_1) / (elev_pt2+precip_2); if ((d_i!=0)||(d_j!=0)){ if (height_ratio>1.){ grid.grid2D(ii + d_i, jj + d_j) += precip; distributed_precip += precip; } } } } return distributed_precip; } /** `````` Mathias Bavay committed Sep 20, 2013 521 522 523 524 525 526 527 `````` * @brief redistribute precip from steeper slopes to gentler slopes by following the steepest path from top to bottom * and gradually depositing precip during descent * @param dem array of elevations (dem). The slope must have been updated as it is required for the DEM analysis. * @param ta array of air temperatures used to determine if precipitation is rain or snow * @param grid 2D array of precipitation to fill * @author Rob Spence and Mathias Bavay */ `````` 528 529 ``````void Interpol2D::SteepSlopeRedistribution(const DEMObject& dem, const Grid2DObject& ta, Grid2DObject& grid) { `````` Mathias Bavay committed Sep 20, 2013 530 `````` for (size_t jj=1; jj<(grid.nrows-1); jj++) { `````` 531 `````` for (size_t ii=1; ii<(grid.ncols-1); ii++) { `````` Mathias Bavay committed Sep 20, 2013 532 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 558 559 560 561 562 563 564 565 566 567 568 569 570 571 `````` if(grid.grid2D(ii,jj)==IOUtils::nodata) continue; if(ta.grid2D(ii, jj)>273.15) continue; //modify precipitation only for air temperatures at or below freezing const double slope = dem.slope(ii, jj); const double curvature = dem.curvature(ii, jj); if(slope==IOUtils::nodata || curvature==IOUtils::nodata) continue; if(slope<=40.) continue; //redistribution only above 40 degrees //remove all precip above 60 deg or linearly decrease it double precip = (slope>60.)? grid.grid2D(ii, jj) : grid.grid2D(ii, jj) * ((40.-slope)/-30.); grid.grid2D(ii, jj) -= precip; //we will redistribute the precipitation in a different way const double increment = precip / 50.; //break removed precip into smaller amounts to be redistributed double counter = 0.5; //counter will determine amount of precip deposited size_t ii_dest = ii, jj_dest = jj; while(precip>0.) { short d_i, d_j; steepestDescentDisplacement(dem, grid, ii_dest, jj_dest, d_i, d_j); //move to the destination cell ii_dest += d_i; jj_dest += d_j; //if (((ii_dest+d_i)<0) || ((jj_dest+d_j)<0) || ((ii_dest+d_i)>=grid.ncols)|| ((jj_dest+d_j)>=grid.nrows)) { if ((ii_dest==0) || (jj_dest==0) || (ii_dest==(grid.ncols-1))|| (jj_dest==(grid.nrows-1))){ //we are getting out of the domain: deposit local contribution grid.grid2D(ii_dest, jj_dest) += counter*increment; break; } if(d_i==0 && d_j==0) { //local minimum, everything stays here... grid.grid2D(ii_dest, jj_dest) += precip; break; } precip -= depositAroundCell(dem, ii_dest, jj_dest, counter*increment, grid); counter += 0.25; //greater amount of precip is deposited as we move down the slope } } } `````` 572 573 ``````} `````` Mathias Bavay committed Sep 20, 2013 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 ``````/** * @brief Ordinary Kriging matrix formulation * This implements the matrix formulation of Ordinary Kriging, as shown (for example) in * "Statistics for spatial data", Noel A. C. Cressie, John Wiley & Sons, revised edition, 1993, pp122. * @param vecData vector containing the values as measured at the stations * @param vecStations vector of stations * @param dem digital elevation model * @param variogram variogram regression model * @param grid 2D array of precipitation to fill * @author Mathias Bavay */ void Interpol2D::ODKriging(const std::vector& vecData, const std::vector& vecStations, const DEMObject& dem, const Fit1D& variogram, Grid2DObject& grid) { grid.set(dem.ncols, dem.nrows, dem.cellsize, dem.llcorner); size_t nrOfMeasurments = vecStations.size(); //precompute various coordinates in the grid const double llcorner_x = grid.llcorner.getEasting(); const double llcorner_y = grid.llcorner.getNorthing(); const double cellsize = grid.cellsize; Matrix Ginv(nrOfMeasurments+1, nrOfMeasurments+1); //fill the Ginv matrix for(size_t j=1; j<=nrOfMeasurments; j++) { const Coords& st1 = vecStations[j-1].position; const double x1 = st1.getEasting(); const double y1 = st1.getNorthing(); for(size_t i=1; i<=j; i++) { //compute distance between stations const Coords& st2 = vecStations[i-1].position; const double DX = x1-st2.getEasting(); const double DY = y1-st2.getNorthing(); const double distance = Optim::fastSqrt_Q3(DX*DX + DY*DY); Ginv(i,j) = variogram.f(distance); } Ginv(j,j)=1.; //HACK diagonal should contain the nugget... Ginv(nrOfMeasurments+1,j) = 1.; //last line filled with 1s } //fill the upper half (an exact copy of the lower half) for(size_t j=1; j<=nrOfMeasurments; j++) { for(size_t i=j+1; i<=nrOfMeasurments; i++) { Ginv(i,j) = Ginv(j,i); } } //add last column of 1's and a zero for(size_t i=1; i<=nrOfMeasurments; i++) Ginv(i,nrOfMeasurments+1) = 1.; Ginv(nrOfMeasurments+1,nrOfMeasurments+1) = 0.; //invert the matrix Ginv.inv(); Matrix G0(nrOfMeasurments+1, (size_t)1); //now, calculate each point for(size_t j=0; j(i)*cellsize; const double y = llcorner_y+static_cast(j)*cellsize; //fill gamma for(size_t st=0; st