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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 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 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 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 554 555 556 557 558 559 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 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
|
/******************************************************************************
*
* Project: GDAL
* Purpose: GDALZonalStats implementation
* Author: Dan Baston
*
******************************************************************************
* Copyright (c) 2025, ISciences LLC
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_string.h"
#include "gdal_priv.h"
#include "gdal_alg.h"
#include "gdal_utils.h"
#include "ogrsf_frmts.h"
#include "raster_stats.h"
#include "../frmts/mem/memdataset.h"
#include "../frmts/vrt/vrtdataset.h"
#include "ogr_geos.h"
#include <algorithm>
#include <array>
#include <cstring>
#include <limits>
#include <variant>
#include <vector>
#if GEOS_VERSION_MAJOR > 3 || \
(GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 14)
#define GEOS_GRID_INTERSECTION_AVAILABLE 1
#endif
struct GDALZonalStatsOptions
{
CPLErr Init(CSLConstList papszOptions)
{
for (const auto &[key, value] : cpl::IterateNameValue(papszOptions))
{
if (EQUAL(key, "BANDS"))
{
const CPLStringList aosBands(CSLTokenizeString2(
value, ",", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
for (const char *pszBand : aosBands)
{
int nBand = std::atoi(pszBand);
if (nBand <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid band: %s", pszBand);
return CE_Failure;
}
bands.push_back(nBand);
}
}
else if (EQUAL(key, "INCLUDE_FIELDS"))
{
CPLStringList aosFields(CSLTokenizeString2(
value, ",",
CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
CSLT_STRIPENDSPACES));
for (const char *pszField : aosFields)
{
include_fields.push_back(pszField);
}
}
else if (EQUAL(key, "PIXEL_INTERSECTION"))
{
if (EQUAL(value, "DEFAULT"))
{
pixels = DEFAULT;
}
else if (EQUAL(value, "ALL-TOUCHED") ||
EQUAL(value, "ALL_TOUCHED"))
{
pixels = ALL_TOUCHED;
}
else if (EQUAL(value, "FRACTIONAL"))
{
pixels = FRACTIONAL;
}
else
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Unexpected value of PIXEL_INTERSECTION: %s",
value);
return CE_Failure;
}
}
else if (EQUAL(key, "RASTER_CHUNK_SIZE_BYTES"))
{
char *endptr = nullptr;
errno = 0;
const auto memory64 = std::strtoull(value, &endptr, 10);
bool ok = errno != ERANGE && memory64 != ULLONG_MAX &&
endptr == value + strlen(value);
if constexpr (sizeof(memory64) > sizeof(size_t))
{
ok = ok &&
memory64 <= std::numeric_limits<size_t>::max() - 1;
}
if (!ok)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid memory size: %s", value);
return CE_Failure;
}
memory = static_cast<size_t>(memory64);
}
else if (EQUAL(key, "STATS"))
{
stats = CPLStringList(CSLTokenizeString2(
value, ",", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
}
else if (EQUAL(key, "STRATEGY"))
{
if (EQUAL(value, "FEATURE_SEQUENTIAL"))
{
strategy = FEATURE_SEQUENTIAL;
}
else if (EQUAL(value, "RASTER_SEQUENTIAL"))
{
strategy = RASTER_SEQUENTIAL;
}
else
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Unexpected value of STRATEGY: %s", value);
return CE_Failure;
}
}
else if (EQUAL(key, "WEIGHTS_BAND"))
{
weights_band = std::atoi(value);
if (weights_band <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid weights band: %s", value);
return CE_Failure;
}
}
else if (EQUAL(key, "ZONES_BAND"))
{
zones_band = std::atoi(value);
if (zones_band <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid zones band: %s", value);
return CE_Failure;
}
}
else if (EQUAL(key, "ZONES_LAYER"))
{
zones_layer = value;
}
else if (STARTS_WITH(key, "LCO_"))
{
layer_creation_options.SetNameValue(key + strlen("LCO_"),
value);
}
else
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Unexpected zonal stats option: %s", key);
}
}
return CE_None;
}
enum PixelIntersection
{
DEFAULT,
ALL_TOUCHED,
FRACTIONAL,
};
enum Strategy
{
FEATURE_SEQUENTIAL,
RASTER_SEQUENTIAL,
};
PixelIntersection pixels{DEFAULT};
Strategy strategy{FEATURE_SEQUENTIAL};
std::vector<std::string> stats{};
std::vector<std::string> include_fields{};
std::vector<int> bands{};
std::string zones_layer{};
std::size_t memory{0};
int zones_band{};
int weights_band{};
CPLStringList layer_creation_options{};
};
template <typename T = GByte> auto CreateBuffer()
{
return std::unique_ptr<T, VSIFreeReleaser>(nullptr);
}
template <typename T>
void Realloc(T &buf, size_t size1, size_t size2, bool &success)
{
if (!success)
{
return;
}
if constexpr (sizeof(size_t) < sizeof(uint64_t))
{
if (size1 > std::numeric_limits<size_t>::max() / size2)
{
success = false;
CPLError(CE_Failure, CPLE_OutOfMemory,
"Too big memory allocation attempt");
return;
}
}
const auto size = size1 * size2;
auto oldBuf = buf.release();
auto newBuf = static_cast<typename T::element_type *>(
VSI_REALLOC_VERBOSE(oldBuf, size));
if (newBuf == nullptr)
{
VSIFree(oldBuf);
success = false;
}
buf.reset(newBuf);
}
static void CalculateCellCenters(const GDALRasterWindow &window,
const GDALGeoTransform >, double *padfX,
double *padfY)
{
double dfJunk;
double x0 = window.nXOff;
double y0 = window.nYOff;
for (int i = 0; i < window.nXSize; i++)
{
gt.Apply(x0 + i + 0.5, window.nYOff, padfX + i, &dfJunk);
}
for (int i = 0; i < window.nYSize; i++)
{
gt.Apply(x0, y0 + i + 0.5, &dfJunk, padfY + i);
}
}
class GDALZonalStatsImpl
{
public:
enum Stat
{
CENTER_X, // must be first value
CENTER_Y,
COUNT,
COVERAGE,
FRAC,
MAX,
MAX_CENTER_X,
MAX_CENTER_Y,
MEAN,
MIN,
MIN_CENTER_X,
MIN_CENTER_Y,
MINORITY,
MODE,
STDEV,
SUM,
UNIQUE,
VALUES,
VARIANCE,
VARIETY,
WEIGHTED_FRAC,
WEIGHTED_MEAN,
WEIGHTED_SUM,
WEIGHTED_STDEV,
WEIGHTED_VARIANCE,
WEIGHTS,
INVALID, // must be last value
};
static constexpr bool IsWeighted(Stat eStat)
{
return eStat == WEIGHTS || eStat == WEIGHTED_FRAC ||
eStat == WEIGHTED_MEAN || eStat == WEIGHTED_SUM ||
eStat == WEIGHTED_VARIANCE || eStat == WEIGHTED_STDEV;
}
using BandOrLayer = std::variant<GDALRasterBand *, OGRLayer *>;
GDALZonalStatsImpl(GDALDataset &src, GDALDataset &dst, GDALDataset *weights,
BandOrLayer zones, const GDALZonalStatsOptions &options)
: m_src(src), m_weights(weights), m_dst(dst), m_zones(zones),
m_coverageDataType(options.pixels == GDALZonalStatsOptions::FRACTIONAL
? GDT_Float32
: GDT_Byte),
m_options(options),
m_maxCells(options.memory /
std::max(1, GDALGetDataTypeSizeBytes(m_workingDataType)))
{
#ifdef HAVE_GEOS
m_geosContext = OGRGeometry::createGEOSContext();
#endif
}
~GDALZonalStatsImpl()
{
#ifdef HAVE_GEOS
if (m_geosContext)
{
finishGEOS_r(m_geosContext);
}
#endif
}
private:
bool Init()
{
#if !(GEOS_GRID_INTERSECTION_AVAILABLE)
if (m_options.pixels == GDALZonalStatsOptions::FRACTIONAL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Fractional pixel coverage calculation requires a GDAL "
"build against GEOS >= 3.14");
return false;
}
#endif
if (m_options.bands.empty())
{
const int nBands = m_src.GetRasterCount();
if (nBands == 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"GDALRasterZonalStats: input dataset has no bands");
return false;
}
m_options.bands.resize(nBands);
for (int i = 0; i < nBands; i++)
{
m_options.bands[i] = i + 1;
}
}
else
{
for (int nBand : m_options.bands)
{
if (nBand <= 0 || nBand > m_src.GetRasterCount())
{
CPLError(CE_Failure, CPLE_AppDefined,
"GDALRasterZonalStats: Invalid band number: %d",
nBand);
return false;
}
}
}
{
const auto eSrcType = m_src.GetRasterBand(m_options.bands.front())
->GetRasterDataType();
if (GDALDataTypeIsConversionLossy(eSrcType, m_workingDataType))
{
CPLError(CE_Failure, CPLE_AppDefined,
"GDALRasterZonalStats: Source data type %s is not "
"supported",
GDALGetDataTypeName(eSrcType));
return false;
}
}
if (m_weights)
{
if (m_options.weights_band > m_weights->GetRasterCount())
{
CPLError(CE_Failure, CPLE_AppDefined,
"GDALRasterZonalStats: invalid weights band");
return false;
}
const auto eWeightsType =
m_weights->GetRasterBand(m_options.weights_band)
->GetRasterDataType();
if (GDALDataTypeIsConversionLossy(eWeightsType, GDT_Float64))
{
CPLError(CE_Failure, CPLE_AppDefined,
"GDALRasterZonalStats: Weights data type %s is not "
"supported",
GDALGetDataTypeName(eWeightsType));
return false;
}
}
for (const auto &stat : m_options.stats)
{
const auto eStat = GetStat(stat);
switch (eStat)
{
case INVALID:
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid stat: %s",
stat.c_str());
return false;
}
case COVERAGE:
m_stats_options.store_coverage_fraction = true;
break;
case VARIETY:
case MODE:
case MINORITY:
case UNIQUE:
case FRAC:
case WEIGHTED_FRAC:
m_stats_options.store_histogram = true;
break;
case VARIANCE:
case STDEV:
case WEIGHTED_VARIANCE:
case WEIGHTED_STDEV:
m_stats_options.calc_variance = true;
break;
case CENTER_X:
case CENTER_Y:
case MIN_CENTER_X:
case MIN_CENTER_Y:
case MAX_CENTER_X:
case MAX_CENTER_Y:
m_stats_options.store_xy = true;
break;
case VALUES:
m_stats_options.store_values = true;
break;
case WEIGHTS:
m_stats_options.store_weights = true;
break;
case COUNT:
case MIN:
case MAX:
case SUM:
case MEAN:
case WEIGHTED_SUM:
case WEIGHTED_MEAN:
break;
}
if (m_weights == nullptr && IsWeighted(eStat))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Stat %s requires weights but none were provided",
stat.c_str());
return false;
}
}
if (m_src.GetGeoTransform(m_srcGT) != CE_None)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Dataset has no geotransform");
return false;
}
if (!m_srcGT.GetInverse(m_srcInvGT))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Dataset geotransform cannot be inverted");
return false;
}
const OGRSpatialReference *poRastSRS = m_src.GetSpatialRefRasterOnly();
const OGRSpatialReference *poWeightsSRS =
m_weights ? m_weights->GetSpatialRefRasterOnly() : nullptr;
const OGRSpatialReference *poZonesSRS = nullptr;
if (ZonesAreFeature())
{
const OGRLayer *poSrcLayer = std::get<OGRLayer *>(m_zones);
const OGRFeatureDefn *poSrcDefn = poSrcLayer->GetLayerDefn();
poZonesSRS = poSrcLayer->GetSpatialRef();
for (const auto &field : m_options.include_fields)
{
if (poSrcDefn->GetFieldIndex(field.c_str()) == -1)
{
CPLError(CE_Failure, CPLE_AppDefined, "Field %s not found.",
field.c_str());
return false;
}
}
}
else
{
poZonesSRS = std::get<GDALRasterBand *>(m_zones)
->GetDataset()
->GetSpatialRefRasterOnly();
if (!m_options.include_fields.empty())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot include fields from raster zones");
return false;
}
}
CPLStringList aosOptions;
aosOptions.AddNameValue("IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING", "1");
std::vector<const OGRSpatialReference *> inputSRS;
if (poRastSRS && poZonesSRS &&
!poRastSRS->IsSame(poZonesSRS, aosOptions.List()))
{
CPLError(CE_Warning, CPLE_AppDefined,
"Inputs and zones do not have the same SRS");
}
if (poWeightsSRS && poZonesSRS &&
!poWeightsSRS->IsSame(poZonesSRS, aosOptions.List()))
{
CPLError(CE_Warning, CPLE_AppDefined,
"Weights and zones do not have the same SRS");
}
if (poWeightsSRS && poRastSRS &&
!poWeightsSRS->IsSame(poRastSRS, aosOptions.List()))
{
CPLError(CE_Warning, CPLE_AppDefined,
"Inputs and weights do not have the same SRS");
}
return true;
}
gdal::RasterStats<double> CreateStats() const
{
return gdal::RasterStats<double>{m_stats_options};
}
OGRLayer *GetOutputLayer(bool createValueField)
{
std::string osLayerName = "stats";
OGRLayer *poLayer =
m_dst.CreateLayer(osLayerName.c_str(), nullptr,
m_options.layer_creation_options.List());
if (!poLayer)
return nullptr;
if (createValueField)
{
OGRFieldDefn oFieldDefn("value", OFTReal);
if (poLayer->CreateField(&oFieldDefn) != OGRERR_NONE)
return nullptr;
}
if (!m_options.include_fields.empty())
{
const OGRFeatureDefn *poSrcDefn =
std::get<OGRLayer *>(m_zones)->GetLayerDefn();
for (const auto &field : m_options.include_fields)
{
const int iField = poSrcDefn->GetFieldIndex(field.c_str());
// Already checked field names during Init()
if (poLayer->CreateField(poSrcDefn->GetFieldDefn(iField)) !=
OGRERR_NONE)
return nullptr;
}
}
for (int iBand : m_options.bands)
{
auto &aiStatFields = m_statFields[iBand];
aiStatFields.fill(-1);
for (const auto &stat : m_options.stats)
{
const Stat eStat = GetStat(stat);
std::string osFieldName;
if (m_options.bands.size() > 1)
{
osFieldName = CPLSPrintf("%s_band_%d", stat.c_str(), iBand);
}
else
{
osFieldName = stat;
}
OGRFieldDefn oFieldDefn(osFieldName.c_str(),
GetFieldType(eStat));
if (poLayer->CreateField(&oFieldDefn) != OGRERR_NONE)
return nullptr;
const int iNewField =
poLayer->GetLayerDefn()->GetFieldIndex(osFieldName.c_str());
aiStatFields[eStat] = iNewField;
}
}
return poLayer;
}
static const char *GetString(Stat s)
{
switch (s)
{
case CENTER_X:
return "center_x";
case CENTER_Y:
return "center_y";
case COUNT:
return "count";
case COVERAGE:
return "coverage";
case FRAC:
return "frac";
case MAX:
return "max";
case MAX_CENTER_X:
return "max_center_x";
case MAX_CENTER_Y:
return "max_center_y";
case MEAN:
return "mean";
case MIN:
return "min";
case MIN_CENTER_X:
return "min_center_x";
case MIN_CENTER_Y:
return "min_center_y";
case MINORITY:
return "minority";
case MODE:
return "mode";
case STDEV:
return "stdev";
case SUM:
return "sum";
case UNIQUE:
return "unique";
case VALUES:
return "values";
case VARIANCE:
return "variance";
case VARIETY:
return "variety";
case WEIGHTED_FRAC:
return "weighted_frac";
case WEIGHTED_MEAN:
return "weighted_mean";
case WEIGHTED_SUM:
return "weighted_sum";
case WEIGHTED_STDEV:
return "weighted_stdev";
case WEIGHTED_VARIANCE:
return "weighted_variance";
case WEIGHTS:
return "weights";
case INVALID:
break;
}
return "invalid";
}
static Stat GetStat(const std::string &stat)
{
for (Stat s = CENTER_X; s < INVALID; s = static_cast<Stat>(s + 1))
{
if (stat == GetString(s))
return s;
}
return INVALID;
}
static OGRFieldType GetFieldType(Stat stat)
{
switch (stat)
{
case CENTER_X:
case CENTER_Y:
case COVERAGE:
case FRAC:
case UNIQUE:
case VALUES:
case WEIGHTS:
return OFTRealList;
case VARIETY:
return OFTInteger;
case COUNT:
case MAX:
case MAX_CENTER_X:
case MAX_CENTER_Y:
case MEAN:
case MIN:
case MIN_CENTER_X:
case MIN_CENTER_Y:
case MINORITY:
case MODE:
case STDEV:
case SUM:
case VARIANCE:
case WEIGHTED_FRAC:
case WEIGHTED_MEAN:
case WEIGHTED_SUM:
case WEIGHTED_STDEV:
case WEIGHTED_VARIANCE:
case INVALID:
break;
}
return OFTReal;
}
int GetFieldIndex(int iBand, Stat eStat) const
{
auto it = m_statFields.find(iBand);
if (it == m_statFields.end())
{
return -1;
}
return it->second[eStat];
}
OGREnvelope ToEnvelope(const GDALRasterWindow &window) const
{
OGREnvelope oSnappedGeomExtent;
m_srcGT.Apply(window, oSnappedGeomExtent);
return oSnappedGeomExtent;
}
void SetStatFields(OGRFeature &feature, int iBand,
const gdal::RasterStats<double> &stats) const
{
if (auto iField = GetFieldIndex(iBand, CENTER_X); iField != -1)
{
const auto ¢er_x = stats.center_x();
feature.SetField(iField, static_cast<int>(center_x.size()),
center_x.data());
}
if (auto iField = GetFieldIndex(iBand, CENTER_Y); iField != -1)
{
const auto ¢er_y = stats.center_y();
feature.SetField(iField, static_cast<int>(center_y.size()),
center_y.data());
}
if (auto iField = GetFieldIndex(iBand, COUNT); iField != -1)
{
feature.SetField(iField, stats.count());
}
if (auto iField = GetFieldIndex(iBand, COVERAGE); iField != -1)
{
const auto &cov = stats.coverage_fractions();
std::vector<double> doubleCov(cov.begin(), cov.end());
// TODO: Add float* overload to Feature::SetField to avoid this copy
feature.SetField(iField, static_cast<int>(doubleCov.size()),
doubleCov.data());
}
if (auto iField = GetFieldIndex(iBand, FRAC); iField != -1)
{
const auto count = stats.count();
const auto &freq = stats.freq();
std::vector<double> values;
values.reserve(freq.size());
for (const auto &[_, valueCount] : freq)
{
values.push_back(valueCount.m_sum_ci / count);
}
feature.SetField(iField, static_cast<int>(values.size()),
values.data());
}
if (auto iField = GetFieldIndex(iBand, MAX); iField != -1)
{
const auto &max = stats.max();
if (max.has_value())
feature.SetField(iField, max.value());
}
if (auto iField = GetFieldIndex(iBand, MAX_CENTER_X); iField != -1)
{
const auto &loc = stats.max_xy();
if (loc.has_value())
feature.SetField(iField, loc.value().first);
}
if (auto iField = GetFieldIndex(iBand, MAX_CENTER_Y); iField != -1)
{
const auto &loc = stats.max_xy();
if (loc.has_value())
feature.SetField(iField, loc.value().second);
}
if (auto iField = GetFieldIndex(iBand, MEAN); iField != -1)
{
feature.SetField(iField, stats.mean());
}
if (auto iField = GetFieldIndex(iBand, MIN); iField != -1)
{
const auto &min = stats.min();
if (min.has_value())
feature.SetField(iField, min.value());
}
if (auto iField = GetFieldIndex(iBand, MINORITY); iField != -1)
{
const auto &minority = stats.minority();
if (minority.has_value())
feature.SetField(iField, minority.value());
}
if (auto iField = GetFieldIndex(iBand, MIN_CENTER_X); iField != -1)
{
const auto &loc = stats.min_xy();
if (loc.has_value())
feature.SetField(iField, loc.value().first);
}
if (auto iField = GetFieldIndex(iBand, MIN_CENTER_Y); iField != -1)
{
const auto &loc = stats.min_xy();
if (loc.has_value())
feature.SetField(iField, loc.value().second);
}
if (auto iField = GetFieldIndex(iBand, MODE); iField != -1)
{
const auto &mode = stats.mode();
if (mode.has_value())
feature.SetField(iField, mode.value());
}
if (auto iField = GetFieldIndex(iBand, STDEV); iField != -1)
{
feature.SetField(iField, stats.stdev());
}
if (auto iField = GetFieldIndex(iBand, SUM); iField != -1)
{
feature.SetField(iField, stats.sum());
}
if (auto iField = GetFieldIndex(iBand, UNIQUE); iField != -1)
{
const auto &freq = stats.freq();
std::vector<double> values;
values.reserve(freq.size());
for (const auto &[value, _] : freq)
{
values.push_back(value);
}
feature.SetField(iField, static_cast<int>(values.size()),
values.data());
}
if (auto iField = GetFieldIndex(iBand, VALUES); iField != -1)
{
const auto &values = stats.values();
feature.SetField(iField, static_cast<int>(values.size()),
values.data());
}
if (auto iField = GetFieldIndex(iBand, VARIANCE); iField != -1)
{
feature.SetField(iField, stats.variance());
}
if (auto iField = GetFieldIndex(iBand, VARIETY); iField != -1)
{
feature.SetField(iField, static_cast<GIntBig>(stats.variety()));
}
if (auto iField = GetFieldIndex(iBand, WEIGHTED_FRAC); iField != -1)
{
const auto count = stats.count();
const auto &freq = stats.freq();
std::vector<double> values;
values.reserve(freq.size());
for (const auto &[_, valueCount] : freq)
{
// Add std::numeric_limits<double>::min() to please Coverity Scan
values.push_back(valueCount.m_sum_ciwi /
(count + std::numeric_limits<double>::min()));
}
feature.SetField(iField, static_cast<int>(values.size()),
values.data());
}
if (auto iField = GetFieldIndex(iBand, WEIGHTED_MEAN); iField != -1)
{
feature.SetField(iField, stats.weighted_mean());
}
if (auto iField = GetFieldIndex(iBand, WEIGHTED_STDEV); iField != -1)
{
feature.SetField(iField, stats.weighted_stdev());
}
if (auto iField = GetFieldIndex(iBand, WEIGHTED_SUM); iField != -1)
{
feature.SetField(iField, stats.weighted_sum());
}
if (auto iField = GetFieldIndex(iBand, WEIGHTED_VARIANCE); iField != -1)
{
feature.SetField(iField, stats.weighted_variance());
}
if (auto iField = GetFieldIndex(iBand, WEIGHTED_SUM); iField != -1)
{
feature.SetField(iField, stats.weighted_sum());
}
if (auto iField = GetFieldIndex(iBand, WEIGHTS); iField != -1)
{
const auto &weights = stats.weights();
feature.SetField(iField, static_cast<int>(weights.size()),
weights.data());
}
}
public:
bool ZonesAreFeature() const
{
return std::holds_alternative<OGRLayer *>(m_zones);
}
bool Process(GDALProgressFunc pfnProgress, void *pProgressData)
{
if (ZonesAreFeature())
{
if (m_options.strategy == GDALZonalStatsOptions::RASTER_SEQUENTIAL)
{
return ProcessVectorZonesByChunk(pfnProgress, pProgressData);
}
return ProcessVectorZonesByFeature(pfnProgress, pProgressData);
}
return ProcessRasterZones(pfnProgress, pProgressData);
}
private:
static std::unique_ptr<GDALDataset>
GetVRT(GDALDataset &src, const GDALDataset &dst, bool &resampled)
{
resampled = false;
GDALGeoTransform srcGT, dstGT;
if (src.GetGeoTransform(srcGT) != CE_None)
{
return nullptr;
}
if (dst.GetGeoTransform(dstGT) != CE_None)
{
return nullptr;
}
CPLStringList aosOptions;
aosOptions.AddString("-of");
aosOptions.AddString("VRT");
aosOptions.AddString("-ot");
aosOptions.AddString("Float64");
// Prevent warning message about Computed -srcwin outside source raster extent.
// We've already tested for this an issued a more understandable message.
aosOptions.AddString("--no-warn-about-outside-window");
if (srcGT != dstGT || src.GetRasterXSize() != dst.GetRasterXSize() ||
src.GetRasterYSize() != dst.GetRasterYSize())
{
const double dfColOffset =
std::fmod(std::abs(srcGT.xorig - dstGT.xorig), dstGT.xscale);
const double dfRowOffset =
std::fmod(std::abs(srcGT.yorig - dstGT.yorig), dstGT.yscale);
OGREnvelope oDstEnv;
dst.GetExtent(&oDstEnv);
aosOptions.AddString("-projwin");
aosOptions.AddString(CPLSPrintf("%.17g", oDstEnv.MinX));
aosOptions.AddString(CPLSPrintf("%.17g", oDstEnv.MaxY));
aosOptions.AddString(CPLSPrintf("%.17g", oDstEnv.MaxX));
aosOptions.AddString(CPLSPrintf("%.17g", oDstEnv.MinY));
if (srcGT.xscale != dstGT.xscale || srcGT.yscale != dstGT.yscale ||
std::abs(dfColOffset) > 1e-4 || std::abs(dfRowOffset) > 1e-4)
{
resampled = true;
aosOptions.AddString("-r");
aosOptions.AddString("average");
}
aosOptions.AddString("-tr");
aosOptions.AddString(CPLSPrintf("%.17g", dstGT.xscale));
aosOptions.AddString(CPLSPrintf("%.17g", std::abs(dstGT.yscale)));
}
std::unique_ptr<GDALDataset> ret;
GDALTranslateOptions *psOptions =
GDALTranslateOptionsNew(aosOptions.List(), nullptr);
ret.reset(GDALDataset::FromHandle(GDALTranslate(
"", GDALDataset::ToHandle(&src), psOptions, nullptr)));
GDALTranslateOptionsFree(psOptions);
return ret;
}
void WarnIfZonesNotCovered(const GDALRasterBand *poZonesBand) const
{
OGREnvelope oZonesEnv;
poZonesBand->GetDataset()->GetExtent(&oZonesEnv);
{
OGREnvelope oSrcEnv;
m_src.GetExtent(&oSrcEnv);
if (!oZonesEnv.Intersects(oSrcEnv))
{
// TODO: Make this an error? Or keep it as a warning but short-circuit to avoid reading pixels?
CPLError(CE_Warning, CPLE_AppDefined,
"Source raster does not intersect zones raster");
}
else if (!oSrcEnv.Contains(oZonesEnv))
{
int bHasNoData;
m_src.GetRasterBand(m_options.bands.front())
->GetNoDataValue(&bHasNoData);
if (bHasNoData)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Source raster does not fully cover zones raster."
"Pixels that do not intersect the values raster "
"will be treated as having a NoData value.");
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Source raster does not fully cover zones raster. "
"Pixels that do not intersect the value raster "
"will be treated as having value of zero.");
}
}
}
if (!m_weights)
{
return;
}
OGREnvelope oWeightsEnv;
m_weights->GetExtent(&oWeightsEnv);
if (!oZonesEnv.Intersects(oWeightsEnv))
{
// TODO: Make this an error? Or keep it as a warning but short-circuit to avoid reading pixels?
CPLError(CE_Warning, CPLE_AppDefined,
"Weighting raster does not intersect zones raster");
}
else if (!oWeightsEnv.Contains(oZonesEnv))
{
int bHasNoData;
m_src.GetRasterBand(m_options.bands.front())
->GetNoDataValue(&bHasNoData);
if (bHasNoData)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Weighting raster does not fully cover zones raster."
"Pixels that do not intersect the weighting raster "
"will be treated as having a NoData weight.");
}
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Weighting raster does not fully cover zones raster. "
"Pixels that do not intersect the weighting raster "
"will be treated as having a weight of zero.");
}
}
}
bool ProcessRasterZones(GDALProgressFunc pfnProgress, void *pProgressData)
{
if (!Init())
{
return false;
}
GDALRasterBand *poZonesBand = std::get<GDALRasterBand *>(m_zones);
WarnIfZonesNotCovered(poZonesBand);
OGRLayer *poDstLayer = GetOutputLayer(true);
if (!poDstLayer)
return false;
// Align the src dataset to the zones.
bool resampled;
std::unique_ptr<GDALDataset> poAlignedValuesDS =
GetVRT(m_src, *poZonesBand->GetDataset(), resampled);
if (resampled)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Resampled source raster to match zones using average "
"resampling.");
}
// Align the weighting dataset to the zones.
std::unique_ptr<GDALDataset> poAlignedWeightsDS;
GDALRasterBand *poWeightsBand = nullptr;
if (m_weights)
{
poAlignedWeightsDS =
GetVRT(*m_weights, *poZonesBand->GetDataset(), resampled);
if (!poAlignedWeightsDS)
{
return false;
}
if (resampled)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Resampled weighting raster to match zones using "
"average resampling.");
}
poWeightsBand =
poAlignedWeightsDS->GetRasterBand(m_options.weights_band);
}
std::map<double, std::vector<gdal::RasterStats<double>>> stats;
auto pabyZonesBuf = CreateBuffer();
size_t nBufSize = 0;
const auto windowIteratorWrapper =
poAlignedValuesDS->GetRasterBand(1)->IterateWindows(m_maxCells);
const auto nIterCount = windowIteratorWrapper.count();
uint64_t iWindow = 0;
for (const auto &oWindow : windowIteratorWrapper)
{
const auto nWindowSize = static_cast<size_t>(oWindow.nXSize) *
static_cast<size_t>(oWindow.nYSize);
if (nBufSize < nWindowSize)
{
bool bAllocSuccess = true;
Realloc(m_pabyValuesBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_workingDataType),
bAllocSuccess);
Realloc(pabyZonesBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_zonesDataType),
bAllocSuccess);
Realloc(m_pabyMaskBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_maskDataType),
bAllocSuccess);
if (m_stats_options.store_xy)
{
Realloc(m_padfX, oWindow.nXSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
Realloc(m_padfY, oWindow.nYSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
}
if (poWeightsBand)
{
Realloc(m_padfWeightsBuf, nWindowSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
Realloc(m_pabyWeightsMaskBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_maskDataType),
bAllocSuccess);
}
if (!bAllocSuccess)
{
return false;
}
nBufSize = nWindowSize;
}
if (m_padfX && m_padfY)
{
CalculateCellCenters(oWindow, m_srcGT, m_padfX.get(),
m_padfY.get());
}
if (!ReadWindow(*poZonesBand, oWindow, pabyZonesBuf.get(),
m_zonesDataType))
{
return false;
}
if (poWeightsBand)
{
if (!ReadWindow(
*poWeightsBand, oWindow,
reinterpret_cast<GByte *>(m_padfWeightsBuf.get()),
GDT_Float64))
{
return false;
}
if (!ReadWindow(*poWeightsBand->GetMaskBand(), oWindow,
m_pabyWeightsMaskBuf.get(), GDT_Byte))
{
return false;
}
}
for (size_t i = 0; i < m_options.bands.size(); i++)
{
const int iBand = m_options.bands[i];
GDALRasterBand *poBand =
poAlignedValuesDS->GetRasterBand(iBand);
if (!ReadWindow(*poBand, oWindow, m_pabyValuesBuf.get(),
m_workingDataType))
{
return false;
}
if (!ReadWindow(*poBand->GetMaskBand(), oWindow,
m_pabyMaskBuf.get(), m_maskDataType))
{
return false;
}
size_t ipx = 0;
for (int k = 0; k < oWindow.nYSize; k++)
{
for (int j = 0; j < oWindow.nXSize; j++)
{
// TODO use inner loop to search for a block of constant pixel values.
double zone =
reinterpret_cast<double *>(pabyZonesBuf.get())[ipx];
auto &aoStats = stats[zone];
aoStats.resize(m_options.bands.size(), CreateStats());
aoStats[i].process(
reinterpret_cast<double *>(m_pabyValuesBuf.get()) +
ipx,
m_pabyMaskBuf.get() + ipx,
m_padfWeightsBuf.get()
? m_padfWeightsBuf.get() + ipx
: nullptr,
m_pabyWeightsMaskBuf.get()
? m_pabyWeightsMaskBuf.get() + ipx
: nullptr,
m_padfX ? m_padfX.get() + j : nullptr,
m_padfY ? m_padfY.get() + k : nullptr, 1, 1);
ipx++;
}
}
}
if (pfnProgress != nullptr)
{
++iWindow;
pfnProgress(static_cast<double>(iWindow) /
static_cast<double>(nIterCount),
"", pProgressData);
}
}
for (const auto &[dfValue, zoneStats] : stats)
{
OGRFeature oFeature(poDstLayer->GetLayerDefn());
oFeature.SetField("value", dfValue);
for (size_t i = 0; i < m_options.bands.size(); i++)
{
const auto iBand = m_options.bands[i];
SetStatFields(oFeature, iBand, zoneStats[i]);
}
if (poDstLayer->CreateFeature(&oFeature) != OGRERR_NONE)
{
return false;
}
}
return true;
}
static bool ReadWindow(GDALRasterBand &band,
const GDALRasterWindow &oWindow, GByte *pabyBuf,
GDALDataType dataType)
{
return band.RasterIO(GF_Read, oWindow.nXOff, oWindow.nYOff,
oWindow.nXSize, oWindow.nYSize, pabyBuf,
oWindow.nXSize, oWindow.nYSize, dataType, 0, 0,
nullptr) == CE_None;
}
#ifndef HAVE_GEOS
bool ProcessVectorZonesByChunk(GDALProgressFunc, void *)
{
CPLError(CE_Failure, CPLE_AppDefined,
"The GEOS library is required to iterate over blocks of the "
"input rasters. Processing can be performed by iterating over "
"the input features instead.");
return false;
#else
bool ProcessVectorZonesByChunk(GDALProgressFunc pfnProgress,
void *pProgressData)
{
if (!Init())
{
return false;
}
std::unique_ptr<GDALDataset> poAlignedWeightsDS;
// Align the weighting dataset to the values.
if (m_weights)
{
bool resampled = false;
poAlignedWeightsDS = GetVRT(*m_weights, m_src, resampled);
if (!poAlignedWeightsDS)
{
return false;
}
if (resampled)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Resampled weights to match source raster using "
"average resampling.");
}
}
auto TreeDeleter = [this](GEOSSTRtree *tree)
{ GEOSSTRtree_destroy_r(m_geosContext, tree); };
std::unique_ptr<GEOSSTRtree, decltype(TreeDeleter)> tree(
GEOSSTRtree_create_r(m_geosContext, 10), TreeDeleter);
std::vector<std::unique_ptr<OGRFeature>> features;
std::map<int, std::vector<gdal::RasterStats<double>>> statsMap;
// Construct spatial index of all input features, storing the index
// of the feature.
{
OGREnvelope oGeomExtent;
for (auto &poFeatureIn : *std::get<OGRLayer *>(m_zones))
{
features.emplace_back(poFeatureIn.release());
const OGRGeometry *poGeom = features.back()->GetGeometryRef();
if (poGeom == nullptr || poGeom->IsEmpty())
{
continue;
}
if (poGeom->getDimension() != 2)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Non-polygonal geometry encountered.");
return false;
}
poGeom->getEnvelope(&oGeomExtent);
GEOSGeometry *poEnv = CreateGEOSEnvelope(oGeomExtent);
if (poEnv == nullptr)
{
return false;
}
GEOSSTRtree_insert_r(
m_geosContext, tree.get(), poEnv,
reinterpret_cast<void *>(features.size() - 1));
GEOSGeom_destroy_r(m_geosContext, poEnv);
}
}
for (int iBand : m_options.bands)
{
statsMap[iBand].resize(features.size(), CreateStats());
}
std::vector<void *> aiHits;
auto addHit = [](void *hit, void *hits)
{ static_cast<std::vector<void *> *>(hits)->push_back(hit); };
size_t nBufSize = 0;
const auto windowIteratorWrapper =
m_src.GetRasterBand(m_options.bands.front())
->IterateWindows(m_maxCells);
const auto nIterCount = windowIteratorWrapper.count();
uint64_t iWindow = 0;
for (const auto &oChunkWindow : windowIteratorWrapper)
{
const size_t nWindowSize =
static_cast<size_t>(oChunkWindow.nXSize) *
static_cast<size_t>(oChunkWindow.nYSize);
const OGREnvelope oChunkExtent = ToEnvelope(oChunkWindow);
aiHits.clear();
{
GEOSGeometry *poEnv = CreateGEOSEnvelope(oChunkExtent);
if (poEnv == nullptr)
{
return false;
}
GEOSSTRtree_query_r(m_geosContext, tree.get(), poEnv, addHit,
&aiHits);
GEOSGeom_destroy_r(m_geosContext, poEnv);
}
if (!aiHits.empty())
{
if (nBufSize < nWindowSize)
{
bool bAllocSuccess = true;
Realloc(m_pabyValuesBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_workingDataType),
bAllocSuccess);
Realloc(m_pabyCoverageBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_coverageDataType),
bAllocSuccess);
Realloc(m_pabyMaskBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_maskDataType),
bAllocSuccess);
if (m_stats_options.store_xy)
{
Realloc(m_padfX, oChunkWindow.nXSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
Realloc(m_padfY, oChunkWindow.nYSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
}
if (m_weights != nullptr)
{
Realloc(m_padfWeightsBuf, nWindowSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
Realloc(m_pabyWeightsMaskBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_maskDataType),
bAllocSuccess);
}
if (!bAllocSuccess)
{
return false;
}
nBufSize = nWindowSize;
}
if (m_padfX && m_padfY)
{
CalculateCellCenters(oChunkWindow, m_srcGT, m_padfX.get(),
m_padfY.get());
}
if (m_weights != nullptr)
{
GDALRasterBand *poWeightsBand =
poAlignedWeightsDS->GetRasterBand(
m_options.weights_band);
if (!ReadWindow(
*poWeightsBand, oChunkWindow,
reinterpret_cast<GByte *>(m_padfWeightsBuf.get()),
GDT_Float64))
{
return false;
}
if (!ReadWindow(*poWeightsBand->GetMaskBand(), oChunkWindow,
m_pabyWeightsMaskBuf.get(), GDT_Byte))
{
return false;
}
}
for (int iBand : m_options.bands)
{
GDALRasterBand *poBand = m_src.GetRasterBand(iBand);
if (!(ReadWindow(*poBand, oChunkWindow,
m_pabyValuesBuf.get(),
m_workingDataType) &&
ReadWindow(*poBand->GetMaskBand(), oChunkWindow,
m_pabyMaskBuf.get(), m_maskDataType)))
{
return false;
}
GDALRasterWindow oGeomWindow;
OGREnvelope oGeomExtent;
for (const void *hit : aiHits)
{
const size_t iHit = reinterpret_cast<size_t>(hit);
const auto poGeom = features[iHit]->GetGeometryRef();
// Trim the chunk window to the portion that intersects
// the geometry being processed.
poGeom->getEnvelope(&oGeomExtent);
oGeomExtent.Intersect(oChunkExtent);
if (!m_srcInvGT.Apply(oGeomExtent, oGeomWindow))
{
return false;
}
oGeomWindow.nXOff =
std::max(oGeomWindow.nXOff, oChunkWindow.nXOff);
oGeomWindow.nYOff =
std::max(oGeomWindow.nYOff, oChunkWindow.nYOff);
oGeomWindow.nXSize =
std::min(oGeomWindow.nXSize,
oChunkWindow.nXOff + oChunkWindow.nXSize -
oGeomWindow.nXOff);
oGeomWindow.nYSize =
std::min(oGeomWindow.nYSize,
oChunkWindow.nYOff + oChunkWindow.nYSize -
oGeomWindow.nYOff);
if (oGeomWindow.nXSize <= 0 || oGeomWindow.nYSize <= 0)
continue;
const OGREnvelope oTrimmedEnvelope =
ToEnvelope(oGeomWindow);
if (!CalculateCoverage(
poGeom, oTrimmedEnvelope, oGeomWindow.nXSize,
oGeomWindow.nYSize, m_pabyCoverageBuf.get()))
{
return false;
}
// Because the window used for polygon coverage is not the
// same as the window used for raster values, iterate
// over partial scanlines on the raster window.
const auto nCoverageXOff =
oGeomWindow.nXOff - oChunkWindow.nXOff;
const auto nCoverageYOff =
oGeomWindow.nYOff - oChunkWindow.nYOff;
for (int iRow = 0; iRow < oGeomWindow.nYSize; iRow++)
{
const auto nFirstPx =
(nCoverageYOff + iRow) * oChunkWindow.nXSize +
nCoverageXOff;
UpdateStats(
statsMap[iBand][iHit],
m_pabyValuesBuf.get() +
nFirstPx * GDALGetDataTypeSizeBytes(
m_workingDataType),
m_pabyMaskBuf.get() +
nFirstPx * GDALGetDataTypeSizeBytes(
m_maskDataType),
m_padfWeightsBuf
? m_padfWeightsBuf.get() + nFirstPx
: nullptr,
m_pabyWeightsMaskBuf
? m_pabyWeightsMaskBuf.get() +
nFirstPx * GDALGetDataTypeSizeBytes(
m_maskDataType)
: nullptr,
m_pabyCoverageBuf.get() +
iRow * oGeomWindow.nXSize *
GDALGetDataTypeSizeBytes(
m_coverageDataType),
m_padfX ? m_padfX.get() + nCoverageXOff
: nullptr,
m_padfY ? m_padfY.get() + nCoverageYOff + iRow
: nullptr,
oGeomWindow.nXSize, 1);
}
}
}
}
if (pfnProgress != nullptr)
{
++iWindow;
pfnProgress(static_cast<double>(iWindow) /
static_cast<double>(nIterCount),
"", pProgressData);
}
}
OGRLayer *poDstLayer = GetOutputLayer(false);
if (!poDstLayer)
return false;
for (size_t iFeature = 0; iFeature < features.size(); iFeature++)
{
auto poDstFeature =
std::make_unique<OGRFeature>(poDstLayer->GetLayerDefn());
poDstFeature->SetFrom(features[iFeature].get());
for (int iBand : m_options.bands)
{
SetStatFields(*poDstFeature, iBand, statsMap[iBand][iFeature]);
}
if (poDstLayer->CreateFeature(poDstFeature.get()) != OGRERR_NONE)
{
return false;
}
}
return true;
#endif
}
bool ProcessVectorZonesByFeature(GDALProgressFunc pfnProgress,
void *pProgressData)
{
if (!Init())
{
return false;
}
OGREnvelope oGeomExtent;
GDALRasterWindow oWindow;
std::unique_ptr<GDALDataset> poAlignedWeightsDS;
// Align the weighting dataset to the values.
if (m_weights)
{
bool resampled = false;
poAlignedWeightsDS = GetVRT(*m_weights, m_src, resampled);
if (!poAlignedWeightsDS)
{
return false;
}
if (resampled)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Resampled weights to match source raster using "
"average resampling.");
}
}
size_t nBufSize = 0;
OGRLayer *poSrcLayer = std::get<OGRLayer *>(m_zones);
OGRLayer *poDstLayer = GetOutputLayer(false);
if (!poDstLayer)
return false;
size_t i = 0;
auto nFeatures = poSrcLayer->GetFeatureCount();
GDALRasterWindow oRasterWindow;
oRasterWindow.nXOff = 0;
oRasterWindow.nYOff = 0;
oRasterWindow.nXSize = m_src.GetRasterXSize();
oRasterWindow.nYSize = m_src.GetRasterYSize();
const OGREnvelope oRasterExtent = ToEnvelope(oRasterWindow);
for (const auto &poFeature : *poSrcLayer)
{
const auto *poGeom = poFeature->GetGeometryRef();
oWindow.nXSize = 0;
oWindow.nYSize = 0;
if (poGeom == nullptr || poGeom->IsEmpty())
{
// do nothing
}
else if (poGeom->getDimension() != 2)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Non-polygonal geometry encountered.");
return false;
}
else
{
poGeom->getEnvelope(&oGeomExtent);
if (oGeomExtent.Intersects(oRasterExtent))
{
oGeomExtent.Intersect(oRasterExtent);
if (!m_srcInvGT.Apply(oGeomExtent, oWindow))
{
return false;
}
oWindow.nXOff =
std::max(oWindow.nXOff, oRasterWindow.nXOff);
oWindow.nYOff =
std::max(oWindow.nYOff, oRasterWindow.nYOff);
oWindow.nXSize =
std::min(oWindow.nXSize, oRasterWindow.nXOff +
oRasterWindow.nXSize -
oWindow.nXOff);
oWindow.nYSize =
std::min(oWindow.nYSize, oRasterWindow.nYOff +
oRasterWindow.nYSize -
oWindow.nYOff);
}
}
std::unique_ptr<OGRFeature> poDstFeature(
OGRFeature::CreateFeature(poDstLayer->GetLayerDefn()));
poDstFeature->SetFrom(poFeature.get());
if (oWindow.nXSize == 0 || oWindow.nYSize == 0)
{
const gdal::RasterStats<double> empty(CreateStats());
for (int iBand : m_options.bands)
{
SetStatFields(*poDstFeature, iBand, empty);
}
}
else
{
// Calculate how many rows of raster data we can read in at
// a time while remaining within maxCells.
const int nRowsPerChunk = std::min(
oWindow.nYSize,
std::max(1, static_cast<int>(
m_maxCells /
static_cast<size_t>(oWindow.nXSize))));
const size_t nWindowSize = static_cast<size_t>(oWindow.nXSize) *
static_cast<size_t>(nRowsPerChunk);
if (nBufSize < nWindowSize)
{
bool bAllocSuccess = true;
Realloc(m_pabyValuesBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_workingDataType),
bAllocSuccess);
Realloc(m_pabyCoverageBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_coverageDataType),
bAllocSuccess);
Realloc(m_pabyMaskBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_maskDataType),
bAllocSuccess);
if (m_stats_options.store_xy)
{
Realloc(m_padfX, oWindow.nXSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
Realloc(m_padfY, oWindow.nYSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
}
if (m_weights != nullptr)
{
Realloc(m_padfWeightsBuf, nWindowSize,
GDALGetDataTypeSizeBytes(GDT_Float64),
bAllocSuccess);
Realloc(m_pabyWeightsMaskBuf, nWindowSize,
GDALGetDataTypeSizeBytes(m_maskDataType),
bAllocSuccess);
}
if (!bAllocSuccess)
{
return false;
}
nBufSize = nWindowSize;
}
if (m_padfX && m_padfY)
{
CalculateCellCenters(oWindow, m_srcGT, m_padfX.get(),
m_padfY.get());
}
std::vector<gdal::RasterStats<double>> aoStats;
aoStats.resize(m_options.bands.size(), CreateStats());
for (int nYOff = oWindow.nYOff;
nYOff < oWindow.nYOff + oWindow.nYSize;
nYOff += nRowsPerChunk)
{
GDALRasterWindow oSubWindow;
oSubWindow.nXOff = oWindow.nXOff;
oSubWindow.nXSize = oWindow.nXSize;
oSubWindow.nYOff = nYOff;
oSubWindow.nYSize = std::min(
nRowsPerChunk, oWindow.nYOff + oWindow.nYSize - nYOff);
const auto nCoverageXOff = oSubWindow.nXOff - oWindow.nXOff;
const auto nCoverageYOff = oSubWindow.nYOff - oWindow.nYOff;
const OGREnvelope oSnappedGeomExtent =
ToEnvelope(oSubWindow);
if (!CalculateCoverage(poGeom, oSnappedGeomExtent,
oSubWindow.nXSize, oSubWindow.nYSize,
m_pabyCoverageBuf.get()))
{
return false;
}
if (m_weights != nullptr)
{
GDALRasterBand *poWeightsBand =
poAlignedWeightsDS->GetRasterBand(
m_options.weights_band);
if (!ReadWindow(*poWeightsBand, oSubWindow,
reinterpret_cast<GByte *>(
m_padfWeightsBuf.get()),
GDT_Float64))
{
return false;
}
if (!ReadWindow(*poWeightsBand->GetMaskBand(),
oSubWindow, m_pabyWeightsMaskBuf.get(),
GDT_Byte))
{
return false;
}
}
for (size_t iBandInd = 0; iBandInd < m_options.bands.size();
iBandInd++)
{
GDALRasterBand *poBand =
m_src.GetRasterBand(m_options.bands[iBandInd]);
if (!ReadWindow(*poBand, oSubWindow,
m_pabyValuesBuf.get(),
m_workingDataType))
{
return false;
}
if (!ReadWindow(*poBand->GetMaskBand(), oSubWindow,
m_pabyMaskBuf.get(), m_maskDataType))
{
return false;
}
UpdateStats(
aoStats[iBandInd], m_pabyValuesBuf.get(),
m_pabyMaskBuf.get(), m_padfWeightsBuf.get(),
m_pabyWeightsMaskBuf.get(), m_pabyCoverageBuf.get(),
m_padfX ? m_padfX.get() + nCoverageXOff : nullptr,
m_padfY ? m_padfY.get() + nCoverageYOff : nullptr,
oSubWindow.nXSize, oSubWindow.nYSize);
}
}
for (size_t iBandInd = 0; iBandInd < m_options.bands.size();
iBandInd++)
{
SetStatFields(*poDstFeature, m_options.bands[iBandInd],
aoStats[iBandInd]);
}
}
if (poDstLayer->CreateFeature(poDstFeature.get()) != OGRERR_NONE)
{
return false;
}
if (pfnProgress)
{
pfnProgress(static_cast<double>(i + 1) /
static_cast<double>(nFeatures),
"", pProgressData);
}
i++;
}
return true;
}
void UpdateStats(gdal::RasterStats<double> &stats, const GByte *pabyValues,
const GByte *pabyMask, const double *padfWeights,
const GByte *pabyWeightsMask, const GByte *pabyCoverage,
const double *pdfX, const double *pdfY, size_t nX,
size_t nY) const
{
if (m_coverageDataType == GDT_Float32)
{
stats.process(reinterpret_cast<const double *>(pabyValues),
pabyMask, padfWeights, pabyWeightsMask,
reinterpret_cast<const float *>(pabyCoverage), pdfX,
pdfY, nX, nY);
}
else
{
stats.process(reinterpret_cast<const double *>(pabyValues),
pabyMask, padfWeights, pabyWeightsMask, pabyCoverage,
pdfX, pdfY, nX, nY);
}
}
bool CalculateCoverage(const OGRGeometry *poGeom,
const OGREnvelope &oSnappedGeomExtent, int nXSize,
int nYSize, GByte *pabyCoverageBuf) const
{
#if GEOS_GRID_INTERSECTION_AVAILABLE
if (m_options.pixels == GDALZonalStatsOptions::FRACTIONAL)
{
std::memset(pabyCoverageBuf, 0,
static_cast<size_t>(nXSize) * nYSize *
GDALGetDataTypeSizeBytes(GDT_Float32));
GEOSGeometry *poGeosGeom =
poGeom->exportToGEOS(m_geosContext, true);
if (!poGeosGeom)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to convert geometry to GEOS.");
return false;
}
const bool bRet = GEOSGridIntersectionFractions_r(
m_geosContext, poGeosGeom, oSnappedGeomExtent.MinX,
oSnappedGeomExtent.MinY, oSnappedGeomExtent.MaxX,
oSnappedGeomExtent.MaxY, nXSize, nYSize,
reinterpret_cast<float *>(pabyCoverageBuf));
if (!bRet)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to calculate pixel intersection fractions.");
}
GEOSGeom_destroy_r(m_geosContext, poGeosGeom);
return bRet;
}
else
#endif
{
GDALGeoTransform oCoverageGT;
oCoverageGT.xorig = oSnappedGeomExtent.MinX;
oCoverageGT.xscale = m_srcGT.xscale;
oCoverageGT.xrot = 0;
oCoverageGT.yorig = m_srcGT.yscale < 0 ? oSnappedGeomExtent.MaxY
: oSnappedGeomExtent.MinY;
oCoverageGT.yscale = m_srcGT.yscale;
oCoverageGT.yrot = 0;
// Create a memory dataset that wraps the coverage buffer so that
// we can invoke GDALRasterize
std::unique_ptr<MEMDataset> poMemDS(MEMDataset::Create(
"", nXSize, nYSize, 0, m_coverageDataType, nullptr));
poMemDS->SetGeoTransform(oCoverageGT);
constexpr double dfBurnValue = 255.0;
constexpr int nBand = 1;
MEMRasterBand *poCoverageBand =
new MEMRasterBand(poMemDS.get(), 1, pabyCoverageBuf,
m_coverageDataType, 0, 0, false, nullptr);
poMemDS->AddMEMBand(poCoverageBand);
poCoverageBand->Fill(0);
CPLStringList aosOptions;
if (m_options.pixels == GDALZonalStatsOptions::ALL_TOUCHED)
{
aosOptions.AddString("ALL_TOUCHED=1");
}
OGRGeometryH hGeom =
OGRGeometry::ToHandle(const_cast<OGRGeometry *>(poGeom));
const auto eErr = GDALRasterizeGeometries(
GDALDataset::ToHandle(poMemDS.get()), 1, &nBand, 1, &hGeom,
nullptr, nullptr, &dfBurnValue, aosOptions.List(), nullptr,
nullptr);
return eErr == CE_None;
}
}
#ifdef HAVE_GEOS
GEOSGeometry *CreateGEOSEnvelope(const OGREnvelope &oEnv) const
{
GEOSCoordSequence *seq = GEOSCoordSeq_create_r(m_geosContext, 2, 2);
if (seq == nullptr)
{
return nullptr;
}
GEOSCoordSeq_setXY_r(m_geosContext, seq, 0, oEnv.MinX, oEnv.MinY);
GEOSCoordSeq_setXY_r(m_geosContext, seq, 1, oEnv.MaxX, oEnv.MaxY);
return GEOSGeom_createLineString_r(m_geosContext, seq);
}
#endif
CPL_DISALLOW_COPY_ASSIGN(GDALZonalStatsImpl)
GDALDataset &m_src;
GDALDataset *m_weights;
GDALDataset &m_dst;
const BandOrLayer m_zones;
const GDALDataType m_coverageDataType;
const GDALDataType m_workingDataType = GDT_Float64;
const GDALDataType m_maskDataType = GDT_Byte;
static constexpr GDALDataType m_zonesDataType = GDT_Float64;
GDALGeoTransform m_srcGT{};
GDALGeoTransform m_srcInvGT{};
GDALZonalStatsOptions m_options{};
gdal::RasterStatsOptions m_stats_options{};
size_t m_maxCells{0};
static constexpr auto NUM_STATS = Stat::INVALID + 1;
std::map<int, std::array<int, NUM_STATS>> m_statFields{};
std::unique_ptr<GByte, VSIFreeReleaser> m_pabyCoverageBuf{};
std::unique_ptr<GByte, VSIFreeReleaser> m_pabyMaskBuf{};
std::unique_ptr<GByte, VSIFreeReleaser> m_pabyValuesBuf{};
std::unique_ptr<double, VSIFreeReleaser> m_padfWeightsBuf{};
std::unique_ptr<GByte, VSIFreeReleaser> m_pabyWeightsMaskBuf{};
std::unique_ptr<double, VSIFreeReleaser> m_padfX{};
std::unique_ptr<double, VSIFreeReleaser> m_padfY{};
#ifdef HAVE_GEOS
GEOSContextHandle_t m_geosContext{nullptr};
#endif
};
static CPLErr GDALZonalStats(GDALDataset &srcDataset, GDALDataset *poWeights,
GDALDataset &zonesDataset, GDALDataset &dstDataset,
const GDALZonalStatsOptions &options,
GDALProgressFunc pfnProgress, void *pProgressData)
{
int nZonesBand = options.zones_band;
std::string osZonesLayer = options.zones_layer;
if (nZonesBand < 1 && osZonesLayer.empty())
{
if (zonesDataset.GetRasterCount() + zonesDataset.GetLayerCount() > 1)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Zones dataset has more than one band or layer. Use "
"the --zone-band or --zone-layer argument to specify "
"which should be used.");
return CE_Failure;
}
if (zonesDataset.GetRasterCount() > 0)
{
nZonesBand = 1;
}
else if (zonesDataset.GetLayerCount() > 0)
{
osZonesLayer = zonesDataset.GetLayer(0)->GetName();
}
else
{
CPLError(CE_Failure, CPLE_AppDefined,
"Zones dataset has no band or layer.");
return CE_Failure;
}
}
GDALZonalStatsImpl::BandOrLayer poZones;
if (nZonesBand > 0)
{
if (nZonesBand > zonesDataset.GetRasterCount())
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid zones band: %d",
nZonesBand);
return CE_Failure;
}
GDALRasterBand *poZonesBand = zonesDataset.GetRasterBand(nZonesBand);
if (poZonesBand == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Specified zones band %d not found", nZonesBand);
return CE_Failure;
}
poZones = poZonesBand;
}
else
{
OGRLayer *poZonesLayer =
zonesDataset.GetLayerByName(osZonesLayer.c_str());
if (poZonesLayer == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Specified zones layer '%s' not found",
options.zones_layer.c_str());
return CE_Failure;
}
poZones = poZonesLayer;
}
GDALZonalStatsImpl alg(srcDataset, dstDataset, poWeights, poZones, options);
return alg.Process(pfnProgress, pProgressData) ? CE_None : CE_Failure;
}
/** Compute statistics of raster values within defined zones
*
* @param hSrcDS raster dataset containing values to be summarized
* @param hWeightsDS optional raster dataset containing weights
* @param hZonesDS raster or vector dataset containing zones across which values will be summarized
* @param hOutDS dataset to which output layer will be written
* @param papszOptions list of options
* BANDS: a comma-separated list of band indices to be processed from the
* source dataset. If not present, all bands will be processed.
* INCLUDE_FIELDS: a comma-separated list of field names from the zones
* dataset to be included in output features.
* PIXEL_INTERSECTION: controls which pixels are included in calculations:
* - DEFAULT: use default options to GDALRasterize
* - ALL_TOUCHED: use ALL_TOUCHED option of GDALRasterize
* - FRACTIONAL: calculate fraction of each pixel that is covered
* by the zone. Requires the GEOS library, version >= 3.14.
* RASTER_CHUNK_SIZE_BYTES: sets a maximum amount of raster data to read
* into memory at a single time (from a single source)
* STATS: comma-separated list of stats. The following stats are supported:
* - center_x
* - center_y
* - count
* - coverage
* - frac
* - max
* - max_center_x
* - max_center_y
* - mean
* - min
* - min_center_x
* - min_center_y
* - minority
* - mode
* - stdev
* - sum
* - unique
* - values
* - variance
* - weighted_frac
* - mean
* - weighted_sum
* - weighted_stdev
* - weighted_variance
* - weights
* STRATEGY: determine how to perform processing with vector zones:
* - FEATURE_SEQUENTIAL: iterate over zones, finding raster pixels
* that intersect with each, calculating stats, and writing output
* to hOutDS.
* - RASTER_SEQUENTIAL: iterate over chunks of the raster, finding
* zones that intersect with each chunk and updating stats.
* Features are written to hOutDS after all processing has been
* completed.
* WEIGHTS_BAND: the band to read from WeightsDS
* ZONES_BAND: the band to read from hZonesDS, if hZonesDS is a raster
* ZONES_LAYER: the layer to read from hZonesDS, if hZonesDS is a vector
* LCO_{key}: layer creation option {key}
*
* @param pfnProgress optional progress reporting callback
* @param pProgressArg optional data for progress callback
* @return CE_Failure if an error occurred, CE_None otherwise
*/
CPLErr GDALZonalStats(GDALDatasetH hSrcDS, GDALDatasetH hWeightsDS,
GDALDatasetH hZonesDS, GDALDatasetH hOutDS,
CSLConstList papszOptions, GDALProgressFunc pfnProgress,
void *pProgressArg)
{
VALIDATE_POINTER1(hSrcDS, __func__, CE_Failure);
VALIDATE_POINTER1(hZonesDS, __func__, CE_Failure);
VALIDATE_POINTER1(hOutDS, __func__, CE_Failure);
GDALZonalStatsOptions sOptions;
if (papszOptions)
{
if (auto eErr = sOptions.Init(papszOptions); eErr != CE_None)
{
return eErr;
}
}
return GDALZonalStats(
*GDALDataset::FromHandle(hSrcDS), GDALDataset::FromHandle(hWeightsDS),
*GDALDataset::FromHandle(hZonesDS), *GDALDataset::FromHandle(hOutDS),
sOptions, pfnProgress, pProgressArg);
}
|