DataCube Class#
Lazy time-series cubes#
DatasetCollection stacks per-file reads into a 4-D
(T, B, R, C) lazy dask.array.Array exposed as collection.data.
Workers never serialise a live gdal.Dataset handle — each timestep
opens on demand through pyramids' CachingFileManager.
from pyramids.dataset import DatasetCollection
cube = DatasetCollection.from_files(sorted_tifs)
cube.data # dask.array.Array, (T, B, R, C)
cube.mean(skipna=True) # numpy array (B, R, C)
cube.groupby(months).mean() # dict {month: ndarray}
cube.crop(bbox=(W, S, E, N), epsg=4326) # bbox crop per timestep
cube.to_zarr("out.zarr") # parallel write
cube.to_netcdf("out.nc") # eager CF-1.8 NetCDF (one variable per band)
cube.to_kerchunk("idx.json") # NetCDF/HDF5 only
See Lazy collections for construction
(from_files, from_archive, from_stac, read_multiple_files),
reductions, groupby via flox, and the three serialisation formats
(Zarr / NetCDF / kerchunk).
Install: pip install 'pyramids-gis[lazy,stac,netcdf-lazy]' for the
full surface; the core reductions require only [lazy], and
to_netcdf requires [xarray].
pyramids.dataset.DatasetCollection
#
Time-stacked collection of co-registered rasters.
Holds N rasters that share a spatial template (rows, columns, cell size, CRS) and exposes them as a single logical "cube" along a time axis. Used for multi-temporal analysis (a daily precipitation series, an annual NDVI stack, a model output forecast, …).
The class operates through two distinct backing paths, each serving a different concern. Understanding which methods route through which is the key to using the class correctly.
Path A — per-timestep gdal.Dataset handles (self._datasets)
Backing store is a list of lazy Dataset instances, one
per timestep, populated by the datasets property on first
access. Each Dataset.read_file(path) opens a gdal handle
but does not read pixels — the cost per timestep is one file
descriptor + a small metadata read. Pixel data flows
block-by-block through GDAL when downstream methods invoke
read_array / crop / to_crs etc.
Methods that route through Path A:
* ``iloc(i)``, ``__getitem__``, ``__setitem__``,
``head``, ``tail``, ``first``, ``last``,
``values`` (read-side: derived per-call cube),
``values=`` (write-side: rebuilds the list with
``Dataset.create_from_array(...)`` per slice).
* Per-timestep ops: ``crop``, ``to_crs``, ``align``,
``apply``, ``overlay``, ``to_file``, ``to_cog_stack``.
Each loops the handles via ``_apply_per_timestep`` and
produces a new collection wrapping the per-timestep
results.
* Visualisation: ``plot`` materialises the cube on demand
via ``np.stack([ds.read_array() for ds in datasets])``.
Works for both **file-backed** and **in-memory** collections.
After a mutating op (in-place ``crop``, ``apply``,
``__setitem__``, ``values =``), the collection is in-memory
and Path A continues to work because the new ``Dataset``
instances live in the GDAL ``MEM`` driver.
Path B — dask graph over file paths (self._files)
Backing store is a list of file path strings. The data
property assembles a dask.array.Array of shape
(time, bands, rows, cols) from
[dask.delayed(_read_time_step)(p) for p in self._files].
Workers re-open each path on demand via a process-cached
CachingFileManager — gdal handles never cross the
pickle boundary, only path strings do. This is what makes
the path scale to dask.distributed clusters and to
cubes larger than RAM.
Methods that route through Path B:
* Reductions over the time axis: ``mean``, ``sum``, ``min``,
``max``, ``std``, ``var`` (all via ``_reduce``);
``groupby(...).<reduction>(...)``.
* Out-of-process writes: ``to_zarr`` (streams the cube to
a Zarr store; never holds it all in RAM), ``to_kerchunk``
(pure metadata pass; reads only a few bytes per file).
Works for **file-backed** collections only. After a mutating
op clears ``_files``, Path B raises a clean
``RuntimeError("DatasetCollection.data requires a
file-backed collection. Use DatasetCollection.from_files(...)
to construct one.")``.
Boundary between the two paths
The two paths read different attributes (_datasets vs
_files) — they are not parallel views of the same store
and cannot drift. The collection moves from "file-backed +
usable from both paths" to "in-memory + Path A only" the
moment a mutating op runs. The transition is explicit
(_files = None) and Path B raises clearly when called
on an in-memory collection. There is no silent disagreement.
The cost split is also explicit:
* Path A holds N file descriptors for the lifetime of the
collection; reads happen synchronously per-method.
* Path B holds zero handles at rest; reads happen inside
dask tasks and share the process-global LRU
(``pyramids.base._file_manager.FILE_CACHE``, default 128
handles) — workers re-using the same path hit the same
cache slot regardless of which dask task opened it first.
Pickle
__getstate__ drops the lazy _datasets cache so
pickle stores only the canonical metadata + paths. The
post-unpickle instance re-opens lazily on first access.
gdal handles never cross the pickle boundary, by design.
See Also
:class:pyramids.dataset.Dataset — the per-timestep raster
wrapped by Path A and read on demand by Path B.
:class:_GroupedCollection — Path B view returned by
groupby.
Source code in src/pyramids/dataset/collection.py
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 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 | |
datasets
property
#
Lazy list of per-timestep :class:Dataset handles.
Populates on first access. Three sources, in priority order:
- Caller-provided
datasets=argument to__init__(used by per-timestep ops to wrap their results). files=argument — each path opened as a lazy gdal handle via :meth:Dataset.read_file.- Fallback for legacy
DatasetCollection(src, time_length=N)constructions with neitherfilesnordatasets— the templatesrcis replicatedtime_lengthtimes.
The cache is per-instance and lives until the collection is
garbage-collected. It is dropped on pickle (see
:meth:__getstate__).
base
property
#
base.
Base Dataset
files
property
#
Files.
time_length
property
#
Length of the dataset.
rows
property
#
Number of rows.
shape
property
#
Number of rows.
columns
property
#
Number of columns.
data
property
#
Return a lazy dask.array.Array of shape (T, B, R, C).
Each per-file read is scheduled as a
:func:dask.delayed task that opens the file via
:class:~pyramids.base._file_manager.CachingFileManager
and reads its full array. Workers therefore never
serialise a gdal.Dataset — only the file path crosses the
pickle boundary, which keeps the graph safe under dask.distributed.
Raises:
| Type | Description |
|---|---|
ImportError
|
If the optional |
RuntimeError
|
If the collection was constructed without a
|
meta
property
#
Return the picklable :class:RasterMeta snapshot.
Always accessible without reopening the template dataset — a
snapshot is derived eagerly at construction (see
:meth:__init__) so downstream lazy paths can read geobox +
dtype metadata without paying a GDAL-open cost per call, and
so the whole collection pickles cleanly even if the
_base Dataset handle is closed or points at a /vsimem/
file.
values
property
writable
#
Materialise the per-timestep arrays as a 3D numpy cube.
Derived, not cached. Every access reads each timestep's
first band via :meth:Dataset.read_array and stacks the
result into (time, rows, cols). There is no stored cube
that can drift from the canonical :attr:datasets source;
callers that want repeated access should hold the returned
array locally.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A fresh |
__init__(src, time_length, files=None, *, meta=None, datasets=None, gdal_env=None)
#
Construct DatasetCollection object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Dataset
|
Template :class: |
required |
time_length
|
int
|
Number of timesteps in the collection. |
required |
files
|
list[str] | None
|
Optional list of file paths backing each timestep.
When given, per-timestep ops open each path as a lazy
:class: |
None
|
meta
|
RasterMeta | None
|
Optional :class: |
None
|
datasets
|
list[Dataset] | None
|
Optional list of pre-opened
:class: |
None
|
gdal_env
|
dict[str, str] | None
|
Optional GDAL config (e.g. a signer's
|
None
|
Source code in src/pyramids/dataset/collection.py
__getstate__()
#
Pickle state — drop the lazy _datasets cache.
Each Dataset in the cache wraps a live gdal handle that
cannot be pickled. Stripping the cache forces the
post-unpickle instance to re-open files on demand. The
on-disk paths in _files are the canonical truth.
Source code in src/pyramids/dataset/collection.py
__str__()
#
str.
Source code in src/pyramids/dataset/collection.py
__repr__()
#
repr.
Source code in src/pyramids/dataset/collection.py
create_cube(src, dataset_length)
classmethod
#
Create DatasetCollection.
- Create DatasetCollection from a sample raster and
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Dataset
|
Raster object. |
required |
dataset_length
|
int
|
Length of the dataset. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DatasetCollection |
DatasetCollection
|
DatasetCollection object. |
Source code in src/pyramids/dataset/collection.py
groupby(time_labels)
#
Group time steps by per-timestep label.
Returns a view exposing the same reduction surface as
:class:DatasetCollection (mean / sum / min / max / std /
var); each reduction runs once per unique label over the
subset of timesteps carrying that label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_labels
|
Sequence of length |
required |
Returns:
| Name | Type | Description |
|---|---|---|
_GroupedCollection |
_GroupedCollection
|
Lightweight view with |
_GroupedCollection
|
Each call returns a dict |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Source code in src/pyramids/dataset/collection.py
reduce_time(times, *, freq, op, skipna=True)
#
Reduce the time axis by a calendar frequency, grid-attached.
Buckets the timesteps by a pandas offset alias ("1MS", "7D",
"6h", …), reduces each window with op through the existing
:meth:groupby reducer, and wraps each window's result back into a
:class:~pyramids.dataset.Dataset carrying the collection's
geotransform / CRS / no-data — so callers get ready-to-write rasters
instead of the bare {label: ndarray} that :meth:groupby returns.
The per-timestep timestamps are supplied by the caller (times)
because a :class:DatasetCollection does not itself carry a time
coordinate. The reduction runs through :attr:data, so the optional
[lazy] extra (dask; flox recommended) is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
Sequence
|
Per-timestep timestamps, length |
required |
freq
|
str
|
A pandas offset alias naming the window size, e.g. |
required |
op
|
str
|
Reduction operation: one of |
required |
skipna
|
bool
|
When |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
list[tuple[Any, Dataset]]
|
list[tuple[Any, Dataset]]: |
|
list[tuple[Any, Dataset]]
|
per non-empty window, sorted by window label. |
|
the |
list[tuple[Any, Dataset]]
|
class: |
list[tuple[Any, Dataset]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Examples:
- Monthly means of a stack of daily COGs, ready to write:
>>> import pandas as pd # doctest: +SKIP >>> from pyramids.dataset.collection import DatasetCollection # doctest: +SKIP >>> coll = DatasetCollection.from_files(daily_cog_paths) # doctest: +SKIP >>> times = pd.date_range("2022-01-01", periods=coll.time_length, freq="1D") # doctest: +SKIP >>> monthly = coll.reduce_time(times, freq="1MS", op="mean") # doctest: +SKIP >>> label, ds = monthly[0] # doctest: +SKIP >>> ds.write_array # a grid-attached Dataset, not a bare ndarray # doctest: +SKIP
Source code in src/pyramids/dataset/collection.py
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 | |
mean(*, skipna=True)
#
Element-wise mean across the time axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skipna
|
bool
|
When True (default) skip |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Mean array of shape |
Source code in src/pyramids/dataset/collection.py
to_kerchunk(output_path, *, concat_dim='time')
#
Emit a combined kerchunk JSON manifest for the collection.
Produces a single JSON sidecar that points at every timestep's source file — downstream consumers open the entire cube as a lazy Zarr-backed xarray with zero data rewrite.
Currently routes through
:func:pyramids.netcdf._kerchunk.combine_kerchunk, which
handles NetCDF/HDF5 sources. GeoTIFF backing is a follow-on
(kerchunk's tiff support requires tifffile).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path where the manifest JSON is written. |
required | |
concat_dim
|
str
|
Dimension along which to concatenate per-file
coordinates. Default |
'time'
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
The combined manifest. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When kerchunk is not installed. |
RuntimeError
|
When the collection has no files list. |
Source code in src/pyramids/dataset/collection.py
to_zarr(store, *, compute=True, mode='w', storage_options=None)
#
Serialise the 4-D (T, B, R, C) cube to a Zarr store.
Each dask chunk in self.data lands in an independent Zarr
chunk file — the only truly parallel raster output path pyramids
offers. Geobox metadata (epsg, geotransform, nodata, band_names,
time_length) is written as attributes on the root group + the
data array following the standard crs_wkt / GeoTransform
attribute convention, so downstream xr.open_zarr(store) consumers
can reconstruct the geobox without pyramids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
Target store (path, fsspec URL, or zarr.Store). |
required | |
compute
|
bool
|
|
True
|
mode
|
str
|
Zarr open mode, typically |
'w'
|
storage_options
|
dict | None
|
Optional dict forwarded to
:func: |
None
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
on |
Raises:
| Type | Description |
|---|---|
OptionalPackageDoesNotExist
|
When the |
RuntimeError
|
When the collection has no files list. |
Source code in src/pyramids/dataset/collection.py
to_netcdf(path, *, time_dim='time', time_coords=None, var_per_band=True)
#
Write the collection's (T, B, Y, X) cube to a single NetCDF.
Materialises every timestep in memory, builds an
:class:xarray.Dataset, and hands it to
:meth:pyramids.netcdf.NetCDF.from_xarray (which routes through
pyramids' own GDAL multidimensional NetCDF writer — no
netcdf4 / h5netcdf engine plug-in needed). The result is
a self-describing NetCDF with one variable per band (CF-1.8
Conventions attr; geobox attached as crs_wkt /
GeoTransform root attrs).
For huge cubes prefer :meth:to_zarr — this writer is
eager (materialises the full T×B×Y×X array) since
NetCDF.from_xarray itself materialises.
No-data values are written as a nodata attribute on the root
group and on each data variable. GDAL's multidim NetCDF writer
rejects CF's standard _FillValue attribute via this code
path, so the round-trip uses nodata for compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output |
required |
time_dim
|
str
|
Name of the time dimension. Default |
'time'
|
time_coords
|
'Sequence[Any] | None'
|
Sequence of length |
None
|
var_per_band
|
bool
|
When |
True
|
Raises:
| Type | Description |
|---|---|
OptionalPackageDoesNotExist
|
When |
ValueError
|
When |
RuntimeError
|
When :meth: |
Examples:
- Stack two single-band rasters into one NetCDF and reopen it:
>>> import os, tempfile >>> import numpy as np >>> from pyramids.dataset import Dataset, DatasetCollection >>> from pyramids.netcdf import NetCDF >>> d = tempfile.mkdtemp() >>> paths = [] >>> for i in range(2): ... arr = (np.arange(20, dtype="int16").reshape(4, 5) + 100 * i) ... p = os.path.join(d, f"t{i}.tif") ... _ = Dataset.create_from_array( ... arr, top_left_corner=(0, 0), cell_size=0.05, epsg=4326, ... no_data_value=-9999, path=p, ... ).close() ... paths.append(p) >>> col = DatasetCollection.from_files(paths) >>> out = os.path.join(d, "cube.nc") >>> col.to_netcdf(out) >>> nc = NetCDF.read_file(out) >>> "Band_1" in nc.variables True >>> nc.epsg 4326
See Also
- :meth:
to_zarr: parallel chunk-by-chunk writer; preferred for very large cubes. - :meth:
to_kerchunk: emit a sidecar that points back at the source files without rewriting data. - :meth:
pyramids.netcdf.NetCDF.from_xarray: the underlying writer.
Source code in src/pyramids/dataset/collection.py
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 | |
from_stac(items, asset, *, patch_url=None, bbox=None, max_items=None, signer=None, align=True, skip_missing=False, groupby=None, like=None, crs=None, resolution=None, bounds=None, anchor='edge')
classmethod
#
Build a collection from a STAC ItemCollection.
Thin forwarder to :func:pyramids.dataset._stac.from_stac.
Duck-typed — accepts :class:pystac.Item objects, raw JSON
dicts, or any iterable of items with .assets + .bbox
semantics. pyramids does not depend on pystac.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable of STAC Items (pystac objects, raw JSON dicts, or any duck-typed equivalent). |
required | |
asset
|
str | Sequence[str]
|
A single asset key ( |
required |
patch_url
|
Optional low-level callable rewriting each href
(runs before |
None
|
|
bbox
|
tuple | None
|
M6 — optional |
None
|
max_items
|
int | None
|
M6 — cap the number of items consumed (after bbox filtering). Useful for quick-look workflows. |
None
|
signer
|
Any
|
Optional signer (e.g. a
:class: |
None
|
align
|
bool
|
Multi-asset only — resample assets at differing
resolutions onto the first asset's grid ( |
True
|
skip_missing
|
bool
|
Drop items missing any requested asset
( |
False
|
groupby
|
str | None
|
|
None
|
like
|
Any
|
Optional target-grid :class: |
None
|
crs
|
int | str | None
|
Target CRS for an explicit grid (with |
None
|
resolution
|
float | None
|
Target pixel size for an explicit grid. |
None
|
bounds
|
Target |
None
|
|
anchor
|
str
|
Grid-snap rule for the explicit grid ( |
'edge'
|
Returns:
| Name | Type | Description |
|---|---|---|
DatasetCollection |
DatasetCollection
|
File-backed collection (or grid-aligned |
DatasetCollection
|
collection when |
Source code in src/pyramids/dataset/collection.py
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 | |
from_point(lat, lon, *, collection, bands, start_date, end_date, edge_size, resolution, units='px', stac=None, query=None, signer=None, align=True)
classmethod
#
Build a point-centred STAC cube (cubo-style convenience constructor).
Thin forwarder to :func:pyramids.dataset._stac.from_point: reprojects
(lat, lon) to its local UTM, snaps to the resolution grid, expands to
an edge_size-pixel (or -metre) square AOI, searches collection over
that AOI + date range, and stacks the bands via :meth:from_stac.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lat
|
float
|
Center latitude in degrees (EPSG:4326). |
required |
lon
|
float
|
Center longitude in degrees (EPSG:4326). |
required |
collection
|
str
|
STAC collection id to search. |
required |
bands
|
A single asset key or a sequence (multi-asset band axis). |
required | |
start_date
|
str
|
Search start ( |
required |
end_date
|
str
|
Search end ( |
required |
edge_size
|
int
|
Cube side length, in pixels ( |
required |
resolution
|
float
|
Pixel size in metres. |
required |
units
|
str
|
|
'px'
|
stac
|
str | None
|
STAC API root URL; |
None
|
query
|
Any
|
Optional STAC |
None
|
signer
|
Any
|
Optional signer, forwarded to the search and the reads. |
None
|
align
|
bool
|
Multi-asset resolution policy (see :meth: |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
DatasetCollection |
DatasetCollection
|
A time-stacked cube over the point AOI. |
Source code in src/pyramids/dataset/collection.py
from_files(files, *, meta=None, gdal_env=None)
classmethod
#
Build a collection from a list of files without pre-opening all.
Only the first file is opened eagerly (to derive
:class:RasterMeta). The remaining files are referenced by
path only — lazy readers open them on demand through
:class:~pyramids.base._file_manager.CachingFileManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
files
|
list[str | Path]
|
Sequence of file paths backing each timestep. |
required |
meta
|
RasterMeta | None
|
Optional pre-computed :class: |
None
|
gdal_env
|
dict[str, str] | None
|
Optional GDAL config (e.g. a signer's
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
DatasetCollection |
DatasetCollection
|
A new collection whose |
DatasetCollection
|
matches |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Source code in src/pyramids/dataset/collection.py
from_archive(url_or_path, *, kind='auto', member_glob='*', meta=None)
classmethod
#
Build a collection from the raster members of an archive.
Lists the archive's members (locally or over the network — a remote ZIP
is read via the chained /vsizip//vsicurl/… path) and hands them to
:meth:from_files, so each matching member becomes one timestep. Only
the first member is opened eagerly; the rest are opened on demand.
For "merge all members into one multi-band :class:Dataset" (bands,
not timesteps) use :meth:pyramids.dataset.Dataset.from_archive.
The archive's file name must carry a recognised extension (.zip /
.tar / .tar.gz / .gz) — GDAL's archive handlers key off the
extension. An extension-less download URL (e.g. an Earth Engine
getDownloadURL ending in :getPixels) must first be fetched and
saved with a .zip name (or written to /vsimem/<name>.zip via
:func:osgeo.gdal.FileFromMemBuffer) before calling this.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url_or_path
|
str | Path
|
Path or URL of the archive ( |
required |
kind
|
str
|
Archive kind — |
'auto'
|
member_glob
|
str
|
:mod: |
'*'
|
meta
|
RasterMeta | None
|
Optional pre-computed :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
DatasetCollection |
DatasetCollection
|
A collection whose |
DatasetCollection
|
of matching members. |
Raises:
| Type | Description |
|---|---|
FileFormatNotSupportedError
|
|
FileNotFoundError
|
No member matched |
ValueError
|
|
Source code in src/pyramids/dataset/collection.py
read_multiple_files(path, with_order=False, regex_string='\\d{4}.\\d{2}.\\d{2}', date=True, file_name_data_fmt=None, start=None, end=None, fmt='%Y-%m-%d', extension='.tif')
classmethod
#
read_multiple_files.
- Read rasters from a folder (or list of files) and create a 3D array with the same 2D dimensions as the
first raster and length equal to the number of files.
- All rasters should have the same dimensions.
- If you want to read the rasters with a certain order, the raster file names should contain a date
that follows a consistent format (YYYY.MM.DD / YYYY-MM-DD or YYYY_MM_DD), e.g. "MSWEP_1979.01.01.tif".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | list[str]
|
Path of the folder that contains all the rasters, or a list containing the paths of the rasters to read. |
required |
with_order
|
bool
|
False
|
|
regex_string
|
str
|
A regex string used to locate the date in the file names. Default is r"\d{4}.\d{2}.\d{2}". For example:
|
'\\d{4}.\\d{2}.\\d{2}'
|
date
|
bool
|
True if the number in the file name is a date. Default is True. |
True
|
file_name_data_fmt
|
str
|
None
|
|
start
|
str
|
Start date if you want to read the input raster for a specific period only and not all rasters. If not given, all rasters in the given path will be read. |
None
|
end
|
str
|
End date if you want to read the input rasters for a specific period only. If not given, all rasters in the given path will be read. |
None
|
fmt
|
str
|
Format of the given date in the start/end parameter. |
'%Y-%m-%d'
|
extension
|
str
|
The extension of the files you want to read from the given path. Default is ".tif". |
'.tif'
|
Returns:
| Name | Type | Description |
|---|---|---|
DatasetCollection |
DatasetCollection
|
Instance of the DatasetCollection class. |
Examples:
- Read all rasters in a folder:
>>> from pyramids.dataset import DatasetCollection
>>> raster_folder = "examples/GIS/data/raster-folder"
>>> prec = DatasetCollection.read_multiple_files(raster_folder)
- Read from a pre-collected list without ordering:
>>> raster_folder = Path("examples/GIS/data/raster-folder")
>>> file_list = list(raster_folder.glob("*.tif"))
>>> prec = DatasetCollection.read_multiple_files(file_list, with_order=False)
Source code in src/pyramids/dataset/collection.py
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 | |
open_multi_dataset(band=0)
#
Deprecated no-op (legacy API).
The eager _values cube this method used to populate is
gone. Per-timestep Dataset handles open lazily via
:attr:datasets on first access; the legacy values /
__getitem__ / head / first views materialise on
demand from those handles. There is nothing for this method
to do.
Kept as a callable shim so legacy code that does
dc.open_multi_dataset() before reading .values still
runs without modification. New code should not call it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
band
|
int
|
Ignored. The full per-timestep band selection
happens inside :meth: |
0
|
Source code in src/pyramids/dataset/collection.py
__getitem__(key)
#
Return one or more timestep arrays, indexed along the time axis.
Equivalent to self.values[key] but with one slight
optimisation: an integer key reads only that timestep's
Dataset (never materialises the full cube).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Integer index or slice along the time axis. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 2D array (single int) or a 3D array (slice). |
Source code in src/pyramids/dataset/collection.py
__setitem__(key, value)
#
Replace a single timestep's Dataset with a MEM Dataset built from value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
int
|
Integer index along the time axis. |
required |
value
|
ndarray
|
A 2D |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in src/pyramids/dataset/collection.py
head(n=5)
#
First n timestep arrays as a 3D numpy slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of timesteps. Defaults to 5. |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: |
Source code in src/pyramids/dataset/collection.py
tail(n=-5)
#
Last -n timestep arrays as a 3D numpy slice.
Matches the legacy signature: a NEGATIVE n (the default
-5) means "last 5". Implementation simply does
self.values[n:], so a positive n would skip the first
n rows instead — that's the legacy behaviour and left as
is for back-compat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Negative integer giving the offset from the
end. Defaults to |
-5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: |
Source code in src/pyramids/dataset/collection.py
first()
#
First timestep array (2D).
Cheaper than self.values[0] because it only reads one
timestep instead of the full cube.
last()
#
Last timestep array (2D).
Cheaper than self.values[-1] because it only reads one
timestep instead of the full cube.
iloc(i)
#
Return the Dataset at position i.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
int
|
Index of the timestep to access. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Dataset |
Dataset
|
The lazy |
Dataset
|
Pixel values are not loaded — they're read on demand when |
|
Dataset
|
the caller invokes a method on the returned Dataset. |
Source code in src/pyramids/dataset/collection.py
plot(band=0, exclude_value=None, **kwargs)
#
Render the collection as an animated stack of band slices.
- read the values stored in a given band across every
``Dataset`` in the collection and hand the resulting
``(time, rows, cols)`` array to cleopatra's animation
path.
Implementation note: this method is a thin caller around the
shared :func:pyramids.dataset._plot_helpers.render_array
helper. It stacks one band per Dataset into a 3-D array
and forwards to render_array(..., mode="animate",
animation_axis_values=...). The duplicated ArrayGlyph
construction that used to live here is gone — the helper owns
the cleopatra dispatch and the same code path serves the
single-frame Dataset.plot and the multi-panel
NetCDF.plot facets. See
:mod:pyramids.dataset._plot_helpers for the three-mode
contract.
Parameters:
| Name | Type | Description | Default | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
band
|
int
|
The band you want to get its data. Default is 0. |
0
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
exclude_value
|
Any
|
Value to exclude from the plot. Default is None. |
None
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
**kwargs
|
Any
|
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
ArrayGlyph |
ArrayGlyph
|
A plotting/animation handle (from cleopatra.ArrayGlyph). |
Source code in src/pyramids/dataset/collection.py
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 | |
to_file(path, driver='geotiff', band=0)
#
Save to geotiff format.
saveRaster saves a raster to a path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | list[str]
|
a path includng the name of the raster and extention. |
required |
driver
|
str
|
driver = "geotiff". |
'geotiff'
|
band
|
int
|
band index, needed only in case of ascii drivers. Default is 1. |
0
|
Examples:
- Save to a file:
>>> raster_obj = Dataset.read_file("path/to/file/***.tif")
>>> output_path = "examples/GIS/data/save_raster_test.tif"
>>> raster_obj.to_file(output_path)
Source code in src/pyramids/dataset/collection.py
to_cog_stack(directory, *, pattern='{name}_{i:04d}.tif', name='slice', overwrite=False, **cog_kwargs)
#
Export each time slice of the collection as an individual COG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Output directory; created if missing. |
required |
pattern
|
str
|
Filename template. Placeholders:
The |
'{name}_{i:04d}.tif'
|
name
|
str
|
Replacement for the |
'slice'
|
overwrite
|
bool
|
If |
False
|
**cog_kwargs
|
Any
|
Forwarded verbatim to
:meth: |
{}
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
List of written file paths, in temporal (index) order. |
Raises:
| Type | Description |
|---|---|
DatasetNotFoundError
|
:meth: |
ValueError
|
|
FileExistsError
|
|
Examples:
- Default naming — one COG per slice:
- Custom filename pattern and name prefix:
- Overwrite existing outputs and forward COG options:
Source code in src/pyramids/dataset/collection.py
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 | |
to_crs(to_epsg=3857, method='nearest neighbor', maintain_alignment=False, inplace=False)
#
Reproject every timestep to a target EPSG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to_epsg
|
int
|
Reference number to the new projection (https://epsg.io/) (default 3857, WGS84 web mercator). |
3857
|
method
|
str
|
Resampling technique. Default is "nearest neighbor". See https://gisgeography.com/raster-resampling/. Accepted values are "nearest neighbor", "cubic", "bilinear". |
'nearest neighbor'
|
maintain_alignment
|
bool
|
True to maintain the number of rows and columns of the raster the same after reprojection. Default is False. |
False
|
inplace
|
bool
|
If True, mutate this collection in place and return None.
If False (default), return a new |
False
|
Returns:
| Type | Description |
|---|---|
DatasetCollection | None
|
DatasetCollection | None: New collection when |
DatasetCollection | None
|
|
Examples:
- Reproject every timestep to EPSG:3857 and keep the result:
Source code in src/pyramids/dataset/collection.py
crop(mask=None, inplace=False, touch=True, *, bbox=None, epsg=None)
#
Crop every timestep against mask or a bbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
Dataset | None
|
Dataset object of the mask raster to crop the rasters (to get
the NoData value and its location in the array). Mask should
include the name of the raster and the extension like
"data/dem.tif", or you can read the mask raster using gdal
and use it as the first parameter to the function. Mutually
exclusive with |
None
|
inplace
|
bool
|
If True, mutate this collection in place and return None.
If False (default), return a new |
False
|
touch
|
bool
|
Include the cells that touch the polygon, not only those that lie entirely inside the polygon mask. Default is True. |
True
|
bbox
|
(tuple[float, float, float, float] | None, keyword - only)
|
|
None
|
epsg
|
(Any, keyword - only)
|
CRS for |
None
|
Returns:
| Type | Description |
|---|---|
DatasetCollection | None
|
DatasetCollection | None: New collection when |
DatasetCollection | None
|
|
Examples:
- Crop aligned rasters using a DEM mask:
>>> dem_path = "examples/GIS/data/acc4000.tif"
>>> src_path = "examples/GIS/data/aligned_rasters/"
>>> out_path = "examples/GIS/data/crop_aligned_folder/"
>>> DatasetCollection.crop(dem_path, src_path, out_path)
- Crop every timestep using a
(W, S, E, N)bbox tuple — the FC is built once and reused across timesteps:
>>> import os, tempfile
>>> import numpy as np
>>> from pyramids.dataset import Dataset, DatasetCollection
>>> d = tempfile.mkdtemp()
>>> paths = []
>>> for t in range(2):
... p = os.path.join(d, f"t{t}.tif")
... _ = Dataset.create_from_array(
... (np.arange(100, dtype="int16").reshape(10, 10) * (t + 1)),
... top_left_corner=(0, 0), cell_size=0.05, epsg=4326, path=p,
... ).close()
... paths.append(p)
>>> col = DatasetCollection.from_files(paths)
>>> cropped = col.crop(bbox=(0.1, -0.2, 0.2, -0.1))
>>> cropped.time_length
2
>>> cropped.base.shape
(1, 2, 2)
Source code in src/pyramids/dataset/collection.py
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 2151 2152 2153 | |
align(alignment_src, inplace=False)
#
Align every timestep to alignment_src.
Matches the coordinate system, the number of rows and columns,
and the cell size of every timestep raster to alignment_src.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alignment_src
|
Dataset
|
Dataset to use as the spatial template (CRS, rows, columns). |
required |
inplace
|
bool
|
If True, mutate this collection in place and return None.
If False (default), return a new |
False
|
Returns:
| Type | Description |
|---|---|
DatasetCollection | None
|
DatasetCollection | None: New collection when |
DatasetCollection | None
|
|
Examples:
- Align every timestep to a DEM template:
Source code in src/pyramids/dataset/collection.py
merge(dst, no_data_value='0', init='nan', n='nan', method='last')
#
Merge this collection's timesteps into one raster.
File-backed collections merge their on-disk paths directly.
In-memory collections (legacy DatasetCollection(src,
time_length=N) constructions, anything produced by
crop(inplace=False) / apply() / to_crs(inplace=False) /
align(inplace=False)) are first staged through a temp
directory, merged, and the staging directory is removed
before the call returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dst
|
str | Path
|
Path to the output raster. |
required |
no_data_value
|
float | int | str
|
Assign a specified nodata value to output bands. |
'0'
|
init
|
float | int | str
|
Pre-initialize the output image bands with these values. However, it is not marked as the nodata value in the output file. If only one value is given, the same value is used in all the bands. |
'nan'
|
n
|
float | int | str
|
Ignore pixels from files being merged in with this pixel value. |
'nan'
|
method
|
str
|
Overlap-resolution rule passed to
:func: |
'last'
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in src/pyramids/dataset/collection.py
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 | |
apply(ufunc, *, inplace=False)
#
Apply a function to every timestep raster.
Each timestep Dataset.apply(ufunc) runs over the
in-domain cells of its band; the result is a new
Dataset. The list of new Datasets is wrapped in a
new collection (out-of-place) or replaces this collection's
handles (inplace).
Out-of-place is the default — the previous in-place
signature mutated a shared numpy cube; with the
Dataset-list backing there is no shared cube to mutate
and per-timestep ops always produce a new Dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ufunc
|
Callable
|
Callable universal function (builtin or user defined). See https://numpy.org/doc/stable/reference/ufuncs.html To create a ufunc from a normal function: https://numpy.org/doc/stable/reference/generated/numpy.frompyfunc.html |
required |
inplace
|
bool
|
When True, replace this collection's per-timestep
|
False
|
Returns:
| Type | Description |
|---|---|
DatasetCollection | None
|
DatasetCollection | None: New collection when |
DatasetCollection | None
|
|
Examples:
- Apply a simple modulo operation to each value:
>>> def func(val):
... return val % 2
>>> ufunc = np.frompyfunc(func, 1, 1)
>>> result = collection.apply(ufunc) # doctest: +SKIP
Source code in src/pyramids/dataset/collection.py
overlay(classes_map, exclude_value=None)
#
Overlay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
classes_map
|
Dataset
|
Dataset object for the raster that has classes to overlay with. |
required |
exclude_value
|
float | int
|
Values to exclude from extracted values. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
dict[float, list[float]]
|
dict[float, list[float]]: Dictionary with a list of values in the basemap as keys and for each key a list of all the intersected values in the maps from the path. |