Skip to content

UgridDataset#

Top-level container for UGRID NetCDF mesh data. Provides the user-facing API for reading, writing, inspecting, and operating on unstructured mesh data.

UgridDataset is a thin, GIS-aware facade: its public methods delegate the heavy lifting to the sibling modules of the subpackage (spatial ops, interpolation, I/O, plotting):

Hold "Ctrl" to enable pan & zoom
flowchart LR
    U["UgridDataset"]
    U -->|"clip · subset_by_bounds"| SP["spatial.clip_mesh<br/>spatial.subset_by_bounds"]
    U -->|"to_dataset"| IN["interpolation.mesh_to_grid"]
    U -->|"read_file · to_file"| IO["io.parse_ugrid_topology<br/>io.write_ugrid_topology"]
    U -->|"plot · plot_outline"| PL["plot.plot_mesh_data<br/>plot.plot_mesh_outline"]
    U -->|"metadata"| MD["UgridMetadata"]

See the subpackage overview for how UgridDataset composes Mesh2d, Connectivity, and MeshVariable.

pyramids.netcdf.ugrid.UgridDataset #

Bases: _UgridFacades

Container for UGRID NetCDF mesh data.

Combines mesh topology, data variables, and global attributes into a single object with GIS-aware operations. Does NOT inherit from Dataset or RasterBase — the raster paradigm does not apply to unstructured meshes.

Attributes:

Name Type Description
_mesh

Mesh2d topology instance.

_data_variables

Mapping of variable name to MeshVariable.

_global_attributes

File-level NetCDF attributes.

_topology_info

Parsed UGRID topology metadata.

_crs_wkt

CRS in WKT format.

_file_name

Source file path, if read from disk.

Source code in src/pyramids/netcdf/ugrid/dataset.py
 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
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
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
class UgridDataset(_UgridFacades):
    """Container for UGRID NetCDF mesh data.

    Combines mesh topology, data variables, and global attributes
    into a single object with GIS-aware operations. Does NOT inherit
    from Dataset or RasterBase — the raster paradigm does not
    apply to unstructured meshes.

    Attributes:
        _mesh: Mesh2d topology instance.
        _data_variables: Mapping of variable name to MeshVariable.
        _global_attributes: File-level NetCDF attributes.
        _topology_info: Parsed UGRID topology metadata.
        _crs_wkt: CRS in WKT format.
        _file_name: Source file path, if read from disk.
    """

    def __init__(
        self,
        mesh: Mesh2d,
        data_variables: dict[str, MeshVariable],
        global_attributes: dict[str, Any],
        topology_info: MeshTopologyInfo | None = None,
        crs_wkt: str | None = None,
        file_name: str | None = None,
        volume_topology: VolumeTopology | None = None,
    ):
        """Assemble a dataset from an already-built mesh and its variables.

        The low-level constructor. Prefer :meth:`read_file` for a file, :meth:`from_arrays`
        for raw arrays, or one of the ``from_*`` bridges -- each of those builds the mesh and
        the metadata record and then calls this. It is also what every derivation
        (:meth:`isel`, :meth:`reduce`, :meth:`copy`, ...) calls through ``type(self)(...)``,
        which is how a subclass survives them.

        Args:
            mesh: The topology the variables sit on.
            data_variables: Mapping of variable name to :class:`MeshVariable`. Held by
                reference, not copied, so a caller must not mutate it afterwards.
            global_attributes: The file-level attributes, e.g. ``Conventions``.
            topology_info: The record of the on-disk variable names and the declared
                topology dimension. ``None`` for a mesh built from arrays, where there are
                no file variables to name. Defaults to ``None``.
            crs_wkt: WKT of the mesh CRS. ``None`` leaves the mesh unreferenced, and
                :attr:`epsg` then answers ``None``. Defaults to ``None``.
            file_name: The path this dataset was read from, carried through derivations so a
                :meth:`to_file` round trip and ``repr`` can name it. ``None`` for an
                in-memory mesh. Defaults to ``None``.
            volume_topology: The ragged (per-column) vertical layering for a genuinely 3-D
                mesh — the map from faces to the flat ``volume`` axis that a
                ``location="volume"`` variable is indexed through (issue #1330). ``None`` (the
                default) for a 2-D mesh or a uniform-layer 3-D one, where the dense
                ``(layer, element)`` path applies and :attr:`n_volume` answers ``None``.
        """
        self._mesh = mesh
        self._data_variables = data_variables
        self._global_attributes = global_attributes
        self._topology_info = topology_info
        self._crs_wkt = crs_wkt
        self._file_name = file_name
        self._volume_topology = volume_topology
        self._cached_crs: Any = None

    @classmethod
    def read_file(
        cls,
        path: str | Path,
        mesh_name: str | None = None,
        driver: str | None = None,
        lazy: bool = True,
    ) -> UgridDataset:
        """Open a mesh file.

        UGRID NetCDF is read here. Any other format — 2DM, Selafin, DFSU, XMDF, … — is read by a
        third-party driver registered into the ``pyramids.mesh_drivers`` entry-point group. A
        non-NetCDF suffix is dispatched by detection; a NetCDF suffix is read by the built-in
        reader first, and only a file that opens but carries no UGRID topology falls back to a
        driver claiming that suffix. Either way a successful UGRID read triggers no driver
        discovery, so a ``.nc`` read still pays nothing.

        Resolution order:

        1. ``driver`` given — that driver, or an error. Never falls back.
        2. A ``/vsi`` path or a NetCDF suffix — the built-in UGRID reader. If a NetCDF-suffixed
           file opens but declares no UGRID topology, a registered driver claiming that suffix
           is tried before giving up, so 3Di, TUFLOW FV and other NetCDF-based formats are
           reachable; discovery runs only after the built-in read has already failed.
        3. Otherwise a registered driver claiming the suffix whose ``can_open`` accepts the file.
        4. Nothing claimed it — the built-in reader anyway, so a NetCDF file under an unusual
           suffix still opens exactly as it always did.
        5. That failed too — :class:`UnsupportedMeshFormatError`, naming what is installed.

        Args:
            path: Path to the file. A GDAL virtual-filesystem path
                (``/vsimem/``, ``/vsizip/``, ``/vsicurl/``, …) is passed straight to GDAL
                rather than checked on disk.
            mesh_name: Which topology to read, for a file declaring more than one (see
                :meth:`mesh_names`). ``None`` (the default) takes the first.
            driver: Name of a registered **mesh** driver to use, bypassing detection — the
                name a plugin declares, not a GDAL driver short name. ``None`` (the default)
                resolves as described above.
            lazy: Defer reading variable values until first access. Forwarded to the driver,
                which honours it when it declares ``lazy_data``. The built-in UGRID reader is
                always lazy, so it rejects ``lazy=False`` rather than ignoring it.

        Returns:
            UgridDataset instance.

        Raises:
            FileNotFoundError: If the file does not exist.
            DriverNotExistError: If ``driver`` names a driver that is not installed.
            UnsupportedMeshFormatError: If no installed driver reads the file, and the
                built-in UGRID reader cannot either.
            IsADirectoryError: The path is a directory that no driver claims.
            TypeError: ``lazy=False`` was asked of the built-in UGRID reader, which is always
                lazy and so cannot honour it.
            RuntimeError: GDAL cannot open a file that reached the built-in reader by its
                own suffix. A file whose suffix no driver claimed is reported as
                :class:`UnsupportedMeshFormatError` instead, so this is now the native
                route only.
            ValueError: If no UGRID topology is found in the file, or ``mesh_name`` names
                a topology the file does not declare.
        """
        selected, native = _resolve_read_driver(path, driver)
        if selected is not None:
            result = _read_through_driver(selected, path, mesh_name, cls, lazy)
        else:
            try:
                result = cls._read_ugrid_netcdf(
                    path, mesh_name, wrap_unreadable=not native, lazy=lazy
                )
            except NoMeshTopologyError:
                # A NetCDF file that opened but carries no UGRID topology -- a 3Di or
                # TUFLOW FV result. Only now, after the built-in read has failed, consult a
                # driver claiming the suffix; if none does, the original error stands. `lazy`
                # is forwarded to the driver, which may honour an eager read even though the
                # built-in reader cannot. A genuine UGRID file with `lazy=False` raised
                # TypeError inside `_read_ugrid_netcdf` instead, before reading any geometry.
                fallback = _netcdf_fallback_driver(path, driver)
                if fallback is None:
                    raise
                result = _read_through_driver(fallback, path, mesh_name, cls, lazy)
        return result

    @classmethod
    def _read_ugrid_netcdf(
        cls,
        path: str | Path,
        mesh_name: str | None,
        wrap_unreadable: bool = False,
        lazy: bool = True,
    ) -> UgridDataset:
        """Read a UGRID NetCDF file through GDAL's multidimensional API.

        The built-in reader, unchanged from before driver dispatch existed. It is reached both
        for a NetCDF suffix and as the fallback when no registered driver claims a file.

        Args:
            path: Path to the file, or a GDAL virtual-filesystem name.
            mesh_name: Which topology to read. ``None`` takes the first.
            wrap_unreadable: True when this call is step 4 of :meth:`read_file`'s resolution —
                a file whose suffix no driver claimed. A failure then reports the installed
                drivers rather than only GDAL's complaint, which would misleadingly suggest the
                file is corrupt rather than unsupported.
            lazy: Defer variable values to first access. The built-in reader is always lazy, so
                ``lazy=False`` is rejected with :class:`TypeError` once a topology is confirmed —
                before any geometry is read. Defaults to True.

        Returns:
            UgridDataset instance.

        Raises:
            FileNotFoundError: If the file does not exist.
            UnsupportedMeshFormatError: If GDAL cannot open a file that reached here as a
                fallback from driver detection.
            NoMeshTopologyError: If the file opens but declares no UGRID topology. Subclasses
                :class:`ValueError`, and is what lets a caller fall back to a driver.
            TypeError: If ``lazy=False``; the built-in reader has no eager mode.
            ValueError: If ``mesh_name`` names a topology the file does not declare.
        """
        # A GDAL virtual-filesystem path (/vsimem/, /vsizip/, /vsicurl/, …) is not an OS path:
        # `Path` would mangle the separators and `exists()` would always be False, so hand
        # those straight to GDAL and let it report. `from_bytes` reads through /vsimem/.
        target = str(path)
        if target.startswith("/vsi"):
            opened_name = target
        else:
            path = Path(path)
            if not path.exists():
                raise FileNotFoundError(
                    f"File not found: {Path(path)}"
                )  # pragma: no cover - `_require_existing_file` runs first on every public route
            opened_name = str(path)

        # GDAL exceptions are enabled package-wide (`Config` calls `gdal.UseExceptions()`),
        # so a file no driver recognises normally raises RuntimeError from inside the binding.
        # That is process-global state, though, and any dependency can call
        # `gdal.DontUseExceptions()` -- after which OpenEx answers None and this guard is the
        # difference between naming the file and an `AttributeError: 'NoneType' object has no
        # attribute 'GetRootGroup'`.
        ds = _open_multidim(opened_name, str(path), wrap_unreadable)
        rg = ds.GetRootGroup()
        if rg is None:  # pragma: no cover - no multidim driver answers None here
            # Kept as a clear message rather than letting `parse_ugrid_topology(None)`
            # raise an AttributeError, though every multidim driver that opens a file
            # does expose a root group.
            raise ValueError(f"Cannot get root group from: {path}")

        topologies = parse_ugrid_topology(rg)
        if not topologies:
            raise NoMeshTopologyError(f"No UGRID mesh topology found in: {path}")

        if not lazy:
            # The built-in reader always defers variable values to first `.data` access and has
            # no eager mode, so `lazy=False` cannot be honoured. Raise here -- after topology is
            # confirmed, before `from_gdal_group` reads any geometry -- so the rejection is cheap
            # and both `read_file` and `read_all` get it. A driver-backed file never reaches this:
            # it raised `NoMeshTopologyError` above, and `lazy` is forwarded to the driver instead.
            raise TypeError(
                "lazy=False is not supported for UGRID NetCDF: the built-in reader always defers "
                "variable values to first access. Call `.load_array()` on a variable to read it "
                "now."
            )

        # A file may declare several meshes. The default stays the first one — changing that
        # would silently alter every existing caller — but `mesh_name` picks any of them, and
        # `read_all` reads them all. Without either, a multi-mesh file quietly dropped the rest.
        if mesh_name is None:
            topo_info = topologies[0]
        else:
            available = [topo.mesh_name for topo in topologies]
            chosen = [topo for topo in topologies if topo.mesh_name == mesh_name]
            if not chosen:
                raise ValueError(
                    f"No UGRID topology named {mesh_name!r} in {path}; it declares "
                    f"{available}."
                )
            topo_info = chosen[0]
        mesh = Mesh2d.from_gdal_group(rg, topo_info)

        # Resolve to an absolute path before threading it into the lazy variable loaders:
        # data reads are deferred to first `.data` access (PERF-3), which re-opens the file.
        # A relative path would break that deferred open if the process changed directory in
        # the meantime; the old eager read was immune because it read while still in `read_file`.
        # A virtual-filesystem name is already absolute and has no OS path to resolve.
        source_name = (
            opened_name if opened_name.startswith("/vsi") else str(Path(path).resolve())
        )
        data_variables = _read_data_variables(rg, topo_info, source_name)
        # Re-attach each variable's active (wet/dry) mask from its `<var>_active` companion,
        # and rebuild the ragged volume topology from its companion arrays, if present — both
        # are additive, so a file carrying neither reads exactly as before (issues #1331/#1330).
        _attach_active_masks(rg, data_variables)
        volume_topology = parse_volume_topology(rg, topo_info.mesh_name)
        # Decode the CF time coordinate onto the temporal variables, so `time_values` answers
        # real datetimes instead of positional indices wherever the file supplies the stamps
        # (issue #1381). Inert for a file with no CF time units.
        _decode_time_coordinate(rg, data_variables)

        global_attrs = _read_attributes(rg)

        ds = None

        result = cls(
            mesh=mesh,
            data_variables=data_variables,
            global_attributes=global_attrs,
            topology_info=topo_info,
            crs_wkt=topo_info.crs_wkt,
            file_name=str(path),
            volume_topology=volume_topology,
        )
        return result

    @property
    def mesh(self) -> Mesh2d:
        """The mesh topology."""
        return self._mesh

    @property
    def mesh_name(self) -> str:
        """Name of the mesh topology variable."""
        result = (
            self._topology_info.mesh_name if self._topology_info else DEFAULT_MESH_NAME
        )
        return result

    @property
    def data_variable_names(self) -> list[str]:
        """Names of all data variables."""
        result = list(self._data_variables.keys())
        return result

    @property
    def crs(self) -> CRS | None:
        """CRS as a pyproj.CRS object, or None. Cached after first access."""
        if self._cached_crs is None and self._crs_wkt is not None:
            try:
                self._cached_crs = CRS.from_wkt(self._crs_wkt)
            except Exception:  # nosec B110 - best-effort CRS parse; falls back to None
                pass
        return cast("CRS | None", self._cached_crs)

    @property
    def epsg(self) -> int | None:
        """EPSG code of the CRS, or None."""
        crs = self.crs
        result = crs.to_epsg() if crs is not None else None
        return result

    @property
    def crs_wkt(self) -> str | None:
        """The mesh CRS as WKT, or `None` when there is none that parses.

        Gated on a successful parse rather than returning `_crs_wkt` verbatim.
        `_crs_wkt` is copied straight out of the file and :attr:`crs` tolerates
        an unparseable one on purpose, swallowing the error and reporting no
        CRS. Handing the raw string to a caller would move that parse out from
        under the handler, so a malformed WKT would start raising downstream
        instead of being reported as "no CRS" here.
        """
        return self._crs_wkt if self.crs is not None else None

    def set_crs(self, crs: str | None = None, epsg: int | None = None) -> None:
        """Assign a CRS to a mesh that has none — no reprojection.

        Exactly one of *crs* or *epsg* must be given. The CRS is written
        in place to the dataset **and** the underlying :class:`Mesh2d`,
        so :attr:`epsg`, :attr:`crs_wkt`, and :attr:`crs` all reflect
        the new value immediately.

        This is the complement of :meth:`to_crs`, which *reprojects*
        coordinates. ``set_crs`` only declares the coordinate system the
        existing coordinates are already in.

        Args:
            crs: WKT string describing the CRS.
            epsg: EPSG code (e.g. ``4326``).

        Raises:
            ValueError: If neither *crs* nor *epsg* is provided, or if
                both are provided.
        """
        wkt, crs_obj = resolve_crs(self._mesh, crs=crs, epsg=epsg)
        self._crs_wkt = wkt
        self._cached_crs = crs_obj

    def _mesh_equals(self, other: UgridDataset) -> bool:
        """Compare mesh topology and coordinate arrays."""
        result = np.array_equal(self._mesh.node_x, other._mesh.node_x)
        if result:
            result = np.array_equal(self._mesh.node_y, other._mesh.node_y)
        if result:
            result = np.array_equal(
                self._mesh.face_node_connectivity.data,
                other._mesh.face_node_connectivity.data,
            )
        return result

    @staticmethod
    def _vars_value_equal(
        vars_a: dict[str, MeshVariable],
        vars_b: dict[str, MeshVariable],
    ) -> bool:
        """Compare variable values ignoring nodata/NaN positions."""
        for name in vars_a:
            va, vb = vars_a[name], vars_b[name]
            if va.data is None and vb.data is None:
                continue
            if va.data is None or vb.data is None:
                return False
            if not array_equals(
                np.asarray(va.data),
                np.asarray(vb.data),
                va.nodata,
                vb.nodata,
            ):
                return False
        return True

    def equals(self, other: object) -> bool:
        """Value equality — same mesh, same variable values at non-missing positions.

        Compares node coordinates, face connectivity, CRS (by EPSG),
        variable names, and per-variable values (ignoring positions
        where either side is nodata/NaN).

        Args:
            other: The object to compare against.  Returns ``False``
                immediately if *other* is not a ``UgridDataset``.

        Returns:
            ``True`` when the two datasets are value-equal.

        See Also:
            identical: Strict comparison that also checks dtype,
                nodata sentinels, CRS WKT, and global attributes.
        """
        if not isinstance(other, UgridDataset):
            return False
        result = self._mesh_equals(other)
        if result:
            result = self.epsg == other.epsg
        if result:
            result = set(self._data_variables) == set(other._data_variables)
        if result:
            result = self._vars_value_equal(self._data_variables, other._data_variables)
        return result

    @staticmethod
    def _nodata_matches(a, b) -> bool:
        """Return True when two nodata sentinels are semantically equal."""
        if a is None or b is None:
            return a is b
        if isinstance(a, float) and isinstance(b, float):
            return a == b or (np.isnan(a) and np.isnan(b))
        result: bool = a == b
        return result

    @staticmethod
    def _vars_identical(
        vars_a: dict[str, MeshVariable],
        vars_b: dict[str, MeshVariable],
    ) -> bool:
        """Strict per-variable comparison (dtype, nodata, values)."""
        for name in vars_a:
            va, vb = vars_a[name], vars_b[name]
            if not UgridDataset._nodata_matches(va.nodata, vb.nodata):
                return False
            if va.data is None and vb.data is None:
                continue
            if va.data is None or vb.data is None:
                return False
            if not array_identical(np.asarray(va.data), np.asarray(vb.data)):
                return False
        return True

    def _crs_identical(self, other: UgridDataset) -> bool:
        """Semantic CRS comparison, falling back to WKT string."""
        if self.crs is not None and other.crs is not None:
            return self.crs == other.crs
        return self._crs_wkt == other._crs_wkt

    def identical(self, other: object) -> bool:
        """Strict equality — same dtype, same values, same nodata, same attributes.

        Everything must match exactly, including NaN positions, dtypes,
        nodata sentinels, CRS WKT, and global attributes.

        Args:
            other: The object to compare against.  Returns ``False``
                immediately if *other* is not a ``UgridDataset``.

        Returns:
            ``True`` when the two datasets are bitwise-identical.

        See Also:
            equals: Looser comparison that ignores nodata positions,
                dtype differences, and attribute mismatches.
        """
        if not isinstance(other, UgridDataset):
            return False
        result = self._mesh_equals(other)
        if result:
            result = self._crs_identical(other)
        if result:
            result = self._global_attributes == other._global_attributes
        if result:
            result = set(self._data_variables) == set(other._data_variables)
        if result:
            result = self._vars_identical(self._data_variables, other._data_variables)
        return result

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """Mesh bounding box as (xmin, ymin, xmax, ymax)."""
        return self._mesh.bounds

    @property
    def global_attributes(self) -> dict[str, Any]:
        """File-level NetCDF attributes."""
        return self._global_attributes

    @property
    def n_node(self) -> int:
        """Number of mesh nodes."""
        return self._mesh.n_node

    @property
    def n_face(self) -> int:
        """Number of mesh faces."""
        return self._mesh.n_face

    @property
    def n_edge(self) -> int:
        """Number of mesh edges."""
        return self._mesh.n_edge

    def get_data(self, variable_name: str) -> MeshVariable:
        """Get a data variable by name.

        Args:
            variable_name: Name of the data variable.

        Returns:
            MeshVariable instance.

        Raises:
            KeyError: If the variable name is not found.
        """
        if variable_name not in self._data_variables:
            raise KeyError(
                f"Variable '{variable_name}' not found. "
                f"Available: {self.data_variable_names}"
            )
        result = self._data_variables[variable_name]
        return result

    def __getitem__(self, key: str) -> MeshVariable:
        """Get a data variable by name using bracket notation.

        Args:
            key: The variable name.

        Returns:
            MeshVariable: The variable.

        Raises:
            KeyError: No variable is named ``key``; the message lists the available names.
        """
        return self.get_data(key)

    def __contains__(self, key: str) -> bool:
        """Whether ``key`` names a data variable of this dataset.

        Args:
            key: The variable name to test.

        Returns:
            bool: True when the dataset carries a variable of that name.
        """
        return key in self._data_variables

    def __len__(self) -> int:
        """The number of data variables.

        Returns:
            int: How many data variables the dataset carries. Note this counts *variables*,
            not elements -- :attr:`n_face` / :attr:`n_node` / :attr:`n_edge` are the mesh
            sizes.
        """
        return len(self._data_variables)

    def __iter__(self) -> Any:
        """Iterate over the data variable names.

        Returns:
            Iterator[str]: The variable names, in insertion order -- so ``list(dataset)``
            and ``dataset.keys()`` agree, and ``for name in dataset`` reads like a mapping.
        """
        return iter(self._data_variables)

    def keys(self) -> list[str]:
        """The data variable names (read-only mapping surface).

        Returns:
            list[str]: The names, in insertion order. A list rather than a view, so it does
            not track later edits -- every variable edit returns a new dataset anyway.
        """
        return list(self._data_variables.keys())

    def values(self) -> list[MeshVariable]:
        """The data variables (read-only mapping surface).

        Returns:
            list[MeshVariable]: The variables, in the same order as :meth:`keys`. The
            variables themselves are not copied, so reading ``.data`` on one still fires its
            lazy loader.
        """
        return list(self._data_variables.values())

    def items(self) -> list[tuple[str, MeshVariable]]:
        """The ``(name, variable)`` pairs (read-only mapping surface).

        Returns:
            list[tuple[str, MeshVariable]]: One pair per variable, in insertion order.
        """
        return list(self._data_variables.items())

    def get(self, key: str, default: Any = None) -> MeshVariable | Any:
        """The variable ``key``, or ``default`` when it is absent.

        Args:
            key: The variable name to look up.
            default: What to answer when no variable is named ``key``. Defaults to ``None``.

        Returns:
            MeshVariable | Any: The variable, or ``default``.
        """
        return self._data_variables.get(key, default)

    @property
    def data_vars(self) -> dict[str, MeshVariable]:
        """A copy of the ``{name: variable}`` mapping.

        A fresh dict, so mutating it never changes the dataset — variable edits go through
        :meth:`with_variable` / :meth:`drop_variables` / :meth:`rename_variable`, which each
        return a new dataset.
        """
        return dict(self._data_variables)

    def with_variable(
        self,
        name: str,
        data: np.ndarray,
        *,
        location: str = "face",
        nodata: float | None = None,
    ) -> UgridDataset:
        """Return a new dataset with ``name`` added or replaced.

        UGRID derivations are immutable — unlike ``NetCDF.set_variable`` this does not mutate
        in place but returns a fresh dataset. A 2-D ``data`` array is treated as temporal
        (leading axis = time); a 1-D array is a static per-element variable.

        Args:
            name: Variable name to add or replace.
            data: The values; ``(n_elements,)`` static or ``(n_time, n_elements)`` temporal.
            location: Mesh location — ``"face"``, ``"node"`` or ``"edge"``. Defaults to
                ``"face"``.
            nodata: Optional no-data value for the new variable.

        Returns:
            UgridDataset: A new dataset carrying the variable.
        """
        arr = np.asarray(data)
        variable = MeshVariable(
            name=name,
            location=location,
            mesh_name=self.mesh_name,
            shape=arr.shape,
            nodata=nodata,
            _data=arr,
        )
        new_vars = dict(self._data_variables)
        new_vars[name] = variable
        return self._rebuild(new_vars)

    def drop_variables(self, names: str | list[str]) -> UgridDataset:
        """Return a new dataset without the named variable(s).

        Args:
            names: A variable name, or a list of them, to drop.

        Returns:
            UgridDataset: A new dataset without those variables.

        Raises:
            KeyError: A named variable is not present.
        """
        drop = [names] if isinstance(names, str) else list(names)
        new_vars = dict(self._data_variables)
        for name in drop:
            if name not in new_vars:
                raise KeyError(
                    f"Variable {name!r} not found. Available: {self.data_variable_names}"
                )
            del new_vars[name]
        return self._rebuild(new_vars)

    def rename_variable(self, old: str, new: str) -> UgridDataset:
        """Return a new dataset with variable ``old`` renamed to ``new``.

        Args:
            old: The current variable name.
            new: The new name.

        Returns:
            UgridDataset: A new dataset with the variable renamed.

        Raises:
            KeyError: ``old`` is not present.
            ValueError: ``new`` already names a different variable.
        """
        if old not in self._data_variables:
            raise KeyError(
                f"Variable {old!r} not found. Available: {self.data_variable_names}"
            )
        if new in self._data_variables and new != old:
            raise ValueError(f"Variable {new!r} already exists.")
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if name == old:
                # `replace` keeps the lazy loader and every other field, only re-labelling
                # the variable, so a rename never forces a read.
                new_vars[new] = replace(var, name=new)
            else:
                new_vars[name] = var
        return self._rebuild(new_vars)

    @property
    def metadata(self) -> UgridMetadata:
        """Full metadata summary for this dataset."""
        topo_tuple = (self._topology_info,) if self._topology_info else ()
        data_vars = {name: var.location for name, var in self._data_variables.items()}
        conventions = self._global_attributes.get("Conventions")
        result = UgridMetadata(
            mesh_topologies=topo_tuple,
            data_variables=data_vars,
            global_attributes=self._global_attributes,
            conventions=conventions,
            n_nodes=self.n_node,
            n_faces=self.n_face,
            n_edges=self.n_edge,
        )
        return result

    def to_dataset(
        self,
        variable_name: str,
        cell_size: float,
        method: str = "nearest",
        bounds: tuple[float, float, float, float] | None = None,
        epsg: int | None = None,
        nodata: float = -9999.0,
    ) -> Dataset:
        """Convert a mesh variable to a regular-grid Dataset.

        Interpolates mesh data onto a regular grid and returns a
        standard pyramids Dataset. This is the bridge between
        unstructured (UGRID) and structured (raster) worlds.

        Args:
            variable_name: Name of the data variable to rasterize.
            cell_size: Target grid cell size in coordinate units.
            method: Interpolation method ("nearest" or "linear").
            bounds: Target (xmin, ymin, xmax, ymax). Defaults to mesh bounds.
            epsg: Target EPSG code. Defaults to mesh CRS.
            nodata: No-data value for the output raster.

        Returns:
            pyramids Dataset with the interpolated data.

        Raises:
            KeyError: No variable is named ``variable_name``.
            ValueError: The variable exists but holds no data (nothing was loaded and it
                carries no lazy loader), so there is nothing to interpolate.
        """
        var = self.get_data(variable_name)
        data = var.data
        if data is None:
            raise ValueError(f"Variable '{variable_name}' has no data loaded.")
        if var.has_time:
            # First step along the variable's own time axis (not blindly axis 0, which for
            # a trailing-time variable would take the first face) — see `_element_values`.
            data = np.take(np.asarray(data), 0, axis=cast("int", var.time_index))

        grid_array, geotransform = mesh_to_grid(
            mesh=self._mesh,
            data=data,
            location=var.location,
            cell_size=cell_size,
            method=method,
            bounds=bounds,
            nodata=nodata,
        )

        # `crs_spec` rather than `self.epsg or 4326`: a mesh carrying a projected
        # WKT with no EPSG code has `epsg is None`, and the old default stamped
        # EPSG:4326 onto metre coordinates. That is the case this resolves.
        #
        # The `or 4326` behind it keeps the *other* case as it was. A mesh with
        # no CRS at all -- no code and no WKT -- has always rasterised to WGS 84
        # here, and `to_dataset(...).to_file("out.tif")` writing a GeoTIFF with
        # no CRS instead would be a silent behaviour change for every caller
        # holding such a mesh. Narrowing that default is a decision for its own
        # change, not a side effect of teaching this line about WKT.
        target_epsg = (
            epsg if epsg is not None else crs_spec(self.epsg, self.crs_wkt) or 4326
        )
        result = Dataset.from_array(
            grid_array,
            no_data_value=nodata,
            geo_ref=GeoReference(
                geo=cast(
                    "tuple[float, float, float, float, float, float]", geotransform
                ),
                epsg=target_epsg,
            ),
        )
        return result

    def crop(
        self,
        mask: Any = None,
        touch: bool = True,
        *,
        bbox: tuple[float, float, float, float] | list[float] | None = None,
        epsg: int | None = None,
    ) -> UgridDataset:
        """Crop the mesh to a polygon mask or a bbox — the unstructured-mesh analogue of crop.

        The mesh equivalent of :meth:`pyramids.dataset.Dataset.crop` / :meth:`NetCDF.crop`. Rather
        than warping a raster, it selects the **faces** that fall inside the region (renumbering the
        node connectivity for the resulting sub-mesh) and keeps the data on the surviving elements.
        Delegates to :meth:`clip` for a polygon and :meth:`subset_by_bounds` for a bbox; this method
        exists so the spatial-subset call is named ``crop`` across the raster and mesh classes alike.

        Args:
            mask (Any):
                Polygon mask — a shapely geometry, ``GeoDataFrame``, or ``FeatureCollection``.
                Mutually exclusive with ``bbox``.
            touch (bool):
                Applies only to a polygon ``mask``: if ``True`` (default), keep faces that touch the
                mask boundary; if ``False``, keep only faces fully inside it. Ignored for ``bbox``,
                which always selects faces by its axis-aligned envelope (``subset_by_bounds``).
                Defaults to True.
            bbox (tuple or list of 4 floats, keyword-only):
                ``(west, south, east, north)`` in the mesh CRS, or in ``epsg`` when supplied. Accepts
                a tuple or a list. Selects faces by the axis-aligned envelope; not affected by
                ``touch``. Mutually exclusive with ``mask``.
            epsg (int, keyword-only):
                CRS of ``bbox``. When it differs from the mesh CRS the box is reprojected to the mesh
                CRS and subset by its envelope; when it equals the mesh CRS it is a no-op. Defaults to
                the mesh CRS.

        Returns:
            UgridDataset: A new sub-mesh — faces inside the region, connectivity renumbered, and data
                variables subset to the surviving elements.

        Raises:
            ValueError: If both ``mask`` and ``bbox`` are supplied, if ``bbox`` is not a 4-tuple, or
                if ``epsg`` is given for a ``bbox`` but the mesh has no CRS to reproject into.
            TypeError: If neither ``mask`` nor ``bbox`` is supplied.

        Examples:
            - Crop a mesh to a polygon (faces intersecting it survive):
                ```python
                >>> from shapely.geometry import Polygon
                >>> from pyramids.netcdf import UgridDataset
                >>> ug = UgridDataset.read_file("mesh.nc")                        # doctest: +SKIP
                >>> sub = ug.crop(Polygon([(-1, -1), (0, -1), (0, 1), (-1, 1)]))  # doctest: +SKIP
                >>> sub.n_face <= ug.n_face                                       # doctest: +SKIP
                True

                ```
            - Crop to a bounding box in the mesh's own CRS:
                ```python
                >>> sub = ug.crop(bbox=(-1.0, -1.0, 0.0, 1.0))                    # doctest: +SKIP

                ```

        See Also:
            clip: Polygon-mask subsetting that ``crop`` delegates to when ``mask`` is given.
            subset_by_bounds: Bounding-box subsetting that ``crop`` delegates to when ``bbox`` is
                given.
            pyramids.dataset.Dataset.crop: The raster equivalent on a gridded dataset.
        """
        if bbox is not None:
            if mask is not None:
                raise ValueError("crop accepts either `mask` or `bbox`, not both")
            if len(bbox) != 4:
                raise ValueError(
                    "bbox must be a 4-tuple of (west, south, east, north), "
                    f"got {len(bbox)} value(s)"
                )
            west, south, east, north = bbox
            if epsg is not None and (self.epsg is None or int(epsg) != int(self.epsg)):
                if self.epsg is None:
                    raise ValueError(
                        f"cannot reproject a bbox given in EPSG:{int(epsg)} into a mesh that has no "
                        "CRS; drop epsg to treat the bbox as native coordinates"
                    )
                # Reproject the bbox to the mesh CRS and subset by its envelope, so the bbox path
                # selects faces with the same rule (subset_by_bounds) regardless of the source CRS.
                west, south, east, north = (
                    gpd.GeoSeries([box(west, south, east, north)], crs=epsg)
                    .to_crs(self.epsg)
                    .total_bounds
                )
            result = self.subset_by_bounds(west, south, east, north)
        elif mask is not None:
            result = self.clip(mask, touch=touch)
        else:
            raise TypeError(
                "crop requires a `mask` (polygon) or a `bbox` (west, south, east, north) tuple"
            )
        return result

    def _wrap_subset(
        self, mesh: Mesh2d, data_variables: dict[str, MeshVariable]
    ) -> UgridDataset:
        """Wrap a ``(mesh, data_variables)`` pair from the spatial subsetters into a dataset.

        The spatial subsetting helpers (:func:`clip_mesh` / :func:`subset_by_bounds`) return
        the rebuilt mesh and data variables rather than a dataset (STR-3 — keeps
        ``ugrid.spatial`` independent of this module). This carries the source dataset's
        global attributes / topology info / CRS onto the subset.

        Args:
            mesh: The subset mesh.
            data_variables: The sliced data variables.

        Returns:
            UgridDataset: The wrapped subset.
        """
        return type(self)(
            mesh=mesh,
            data_variables=data_variables,
            global_attributes=self._global_attributes,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
        )

    def clip(self, mask: Any, touch: bool = True) -> UgridDataset:
        """Clip the mesh to a polygon mask.

        Selects faces that intersect (touch=True) or are fully
        contained within (touch=False) the mask polygon.

        Args:
            mask: Polygon mask (GeoDataFrame, FeatureCollection,
                or Shapely geometry).
            touch: If True, include faces touching the boundary.

        Returns:
            New UgridDataset with clipped mesh and data.
        """
        mesh, data_variables = clip_mesh(self, mask, touch=touch)
        return self._wrap_subset(mesh, data_variables)

    def subset_by_bounds(
        self,
        xmin: float,
        ymin: float,
        xmax: float,
        ymax: float,
    ) -> UgridDataset:
        """Subset mesh to faces within a bounding box.

        Args:
            xmin: Minimum x-coordinate.
            ymin: Minimum y-coordinate.
            xmax: Maximum x-coordinate.
            ymax: Maximum y-coordinate.

        Returns:
            New UgridDataset with subset mesh and data.
        """
        mesh, data_variables = subset_by_bounds(self, xmin, ymin, xmax, ymax)
        return self._wrap_subset(mesh, data_variables)

    def to_crs(self, to_epsg: int) -> UgridDataset:
        """Reproject all node coordinates to a new CRS.

        Uses pyproj.Transformer to reproject node coordinates.
        Face/edge center coordinates are recomputed after reprojection.
        Data values are preserved — only coordinates change.

        Args:
            to_epsg: Target EPSG code.

        Returns:
            New UgridDataset with reprojected coordinates.

        Raises:
            ValueError: The mesh declares neither an EPSG code nor a WKT, so there is no
                source CRS to reproject from.
        """
        # The mesh may describe its CRS by WKT alone, with no EPSG code to
        # resolve; `crs_spec` returns whichever of the two is usable, so a
        # projected mesh stops being refused for a CRS it plainly has.
        source_crs = crs_spec(self.epsg, self.crs_wkt)
        if source_crs is None:
            raise ValueError(
                "Cannot reproject: source CRS is unknown. "
                "Set CRS before calling to_crs()."
            )

        # Through `crs_from_user_input` so a mesh in a CRS whose code only GDAL's
        # PROJ database carries still reprojects (issue #943). The source goes in
        # as-is rather than as `EPSG:{...}`: `crs_spec` yields the mesh's WKT when
        # there is no usable code, and prefixing that builds the nonsense
        # `EPSG:PROJCS[...]`. The target is always a bare integer code.
        transformer = Transformer.from_crs(
            crs_from_user_input(source_crs),
            crs_from_user_input(f"EPSG:{to_epsg}"),
            always_xy=True,
        )
        new_node_x, new_node_y = transformer.transform(
            self._mesh.node_x,
            self._mesh.node_y,
        )

        new_face_x = None
        new_face_y = None
        if self._mesh.has_face_coords:
            new_face_x, new_face_y = transformer.transform(
                self._mesh.face_x,
                self._mesh.face_y,
            )

        new_edge_x = None
        new_edge_y = None
        if self._mesh.has_edge_coords:
            new_edge_x, new_edge_y = transformer.transform(
                self._mesh.edge_x,
                self._mesh.edge_y,
            )

        new_mesh = Mesh2d(
            node_x=new_node_x,
            node_y=new_node_y,
            face_node_connectivity=self._mesh.face_node_connectivity,
            edge_node_connectivity=self._mesh.edge_node_connectivity,
            face_edge_connectivity=self._mesh.face_edge_connectivity,
            face_face_connectivity=self._mesh.face_face_connectivity,
            edge_face_connectivity=self._mesh.edge_face_connectivity,
            face_x=new_face_x,
            face_y=new_face_y,
            edge_x=new_edge_x,
            edge_y=new_edge_y,
        )

        srs = sr_from_epsg(to_epsg)
        new_crs_wkt = srs.ExportToWkt()

        new_topo_info = None
        if self._topology_info is not None:
            new_topo_info = replace(self._topology_info, crs_wkt=new_crs_wkt)

        # `type(self)` and `file_name`, as every other derivation does: hard-coding
        # `UgridDataset(` silently downgraded a subclass, and dropping `file_name` made the
        # attribute unreliable rather than absent.
        result = type(self)(
            mesh=new_mesh,
            data_variables=self._data_variables,
            global_attributes=self._global_attributes,
            topology_info=new_topo_info,
            crs_wkt=new_crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )
        return result

    @property
    def time_values(self) -> list | None:
        """Parsed time coordinate values from the first temporal variable.

        Returns None if no variables have a time dimension.
        """
        result = None
        for var in self._data_variables.values():
            if var.has_time:
                time_attr = var.attributes.get("time_values")
                if time_attr is not None:
                    result = list(time_attr)
                else:
                    result = list(range(var.n_time_steps))
                break
        return result

    def sel_time(self, index: int) -> UgridDataset:
        """Select a single time step from all temporal variables.

        Non-temporal variables are kept unchanged.

        Args:
            index: Time step index.

        Returns:
            New UgridDataset with single time step data.
        """
        new_data_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if var.has_time:
                new_data_vars[name] = var.with_data(
                    var.sel_time(index), active=var._time_sliced_active(index, None)
                )
            else:
                new_data_vars[name] = var

        # See `to_crs`: `type(self)` keeps a subclass, and `file_name` is carried.
        result = type(self)(
            mesh=self._mesh,
            data_variables=new_data_vars,
            global_attributes=self._global_attributes,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )
        return result

    def sel_time_range(self, start: int, stop: int) -> UgridDataset:
        """Select a time range from all temporal variables.

        Args:
            start: Start index (inclusive).
            stop: Stop index (exclusive).

        Returns:
            New UgridDataset with the selected time range.
        """
        new_data_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if var.has_time:
                new_data_vars[name] = var.sel_time_range(start, stop)
            else:
                new_data_vars[name] = var

        # See `to_crs`: `type(self)` keeps a subclass, and `file_name` is carried.
        result = type(self)(
            mesh=self._mesh,
            data_variables=new_data_vars,
            global_attributes=self._global_attributes,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )
        return result

    def attach_data(
        self, path: str | Path, driver: str | None = None, lazy: bool = True
    ) -> UgridDataset:
        """Attach a results-only file's variables to this mesh.

        Some formats carry values but no topology — an SMS ``.dat``, an XMDF, an XDMF — and must
        be paired with a mesh read from elsewhere. Those drivers declare ``needs_mesh``, and
        :meth:`read_file` refuses them, pointing here.

            >>> mesh = UgridDataset.read_file("domain.2dm")       # doctest: +SKIP
            >>> result = mesh.attach_data("velocity.dat")         # doctest: +SKIP

        The driver returns **only the variables it read**; this method merges them onto the
        dataset. That division is deliberate — it makes a name the dataset already defines an
        unambiguous collision, and means a driver cannot drop the dataset's own variables by
        rebuilding the mapping.

        The driver checks the file's declared element count against this mesh. That check is the
        only safeguard there is: a bare results file carries nothing identifying the mesh it
        belongs to, so attaching it to the wrong one would otherwise produce a plausible and
        entirely wrong dataset.

        Args:
            path: The results file to read.
            driver: Name of a registered driver to use, bypassing detection. ``None`` (the
                default) picks the ``needs_mesh`` driver claiming the file's suffix.
            lazy: Defer reading variable values until first access. Defaults to True.

        Returns:
            A new dataset carrying this mesh plus the attached variables. This dataset is
            unchanged.

        Raises:
            FileNotFoundError: If the results file does not exist.
            DriverNotExistError: If ``driver`` names a driver that is not installed.
            UnsupportedMeshFormatError: If no installed driver can attach this file, the
                named driver does not declare ``needs_mesh``, or the driver returned
                something other than a mapping of name to :class:`MeshVariable`.
            ValueError: If the driver returns a variable whose name this dataset already
                uses, or reports an element-count mismatch against this mesh.
        """
        _require_existing_file(path)
        selected = _resolve_attach_driver(path, driver)
        produced = _read_data_through_driver(selected, path, self, lazy)
        collisions = sorted(set(produced) & set(self._data_variables))
        if collisions:
            raise ValueError(
                f"The {selected.name!r} driver read variable(s) {collisions} from "
                f"{str(path)!r}, which this dataset already defines. Rename one side before "
                f"attaching, or drop the existing variable first."
            )
        merged = dict(self._data_variables)
        merged.update(produced)
        return type(self)(
            mesh=self._mesh,
            data_variables=merged,
            global_attributes=self._global_attributes,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            volume_topology=self._volume_topology,
            file_name=self._file_name,
        )

    def to_file(
        self, path: str | Path, driver: str | None = None, **options: Any
    ) -> None:
        """Write the dataset to a file.

        Writes UGRID-compliant NetCDF by default: a topology variable, node coordinates,
        connectivity arrays, face/edge centres, data variables, and global attributes following
        the UGRID convention.

        With ``driver``, writes through a registered third-party driver instead — 2DM, Selafin,
        PLY and others are writable. The output format is never inferred from the suffix, so
        ``to_file("mesh.slf")`` still writes NetCDF; name the driver to change that.

        Args:
            path: Output file path.
            driver: Name of a registered **mesh** driver to write with, as declared by the
                plugin providing it (see :func:`~pyramids.netcdf.ugrid.mesh_drivers`) — not a
                GDAL driver short name, which is what ``driver`` means elsewhere in pyramids.
                ``None`` (the default) writes UGRID NetCDF through the built-in writer, and
                the output format is never inferred from ``path``'s suffix.
            **options: Format-specific settings for the driver, passed through uninterpreted
                (for example Selafin endianness, or PLY ascii versus binary). The built-in
                writer takes none, so passing any without a ``driver`` raises ``TypeError``
                rather than dropping them silently.

        Raises:
            DriverNotExistError: If ``driver`` names a driver that is not installed.
            UnsupportedMeshFormatError: If the named driver cannot write a mesh.
            TypeError: If ``options`` are given without a ``driver``.
        """
        if driver is not None:
            self._write_through_driver(path, driver, options)
        elif options:
            raise TypeError(
                f"to_file() got unexpected keyword argument(s) "
                f"{sorted(options)}; format options apply to a `driver=` write only."
            )
        else:
            self._write_ugrid_netcdf(Path(path))

    def to_bytes(self) -> bytes:
        """Serialise the dataset to an in-memory UGRID NetCDF buffer.

        Writes through a temporary file because GDAL's NetCDF driver
        does not support ``/vsimem/`` for multidimensional creation.

        Returns:
            bytes: The NetCDF file content, suitable for writing to
                cloud storage or embedding in a response payload.

        See Also:
            to_file: Write directly to a file on disk.
            read_file: Class method that reads from a file path or
                byte buffer.
        """
        with tempfile.NamedTemporaryFile(suffix=".nc", delete=False) as tmp:
            tmp_path = Path(tmp.name)
        try:
            self._write_ugrid_netcdf(tmp_path)
            data = tmp_path.read_bytes()
        finally:
            try:
                tmp_path.unlink(missing_ok=True)
            except PermissionError:
                pass
        return data

    def _write_ugrid_netcdf(self, path: Path) -> None:
        """Write UGRID-compliant NetCDF through GDAL's multidimensional API.

        The built-in writer, unchanged from before driver dispatch existed.

        Args:
            path: Output file path.
        """
        drv = gdal.GetDriverByName("netCDF")
        ds = drv.CreateMultiDimensional(str(path))
        rg = ds.GetRootGroup()

        mesh_name = self.mesh_name
        dims = write_ugrid_topology(rg, self._mesh, mesh_name, self._crs_wkt)
        if self._volume_topology is not None:
            # Before the data variables, so the `nVolumes` dimension exists when a
            # `location="volume"` variable is written against it (issue #1330).
            write_volume_topology(rg, mesh_name, self._volume_topology, dims)

        _require_one_time_length(self._data_variables)
        for var in self._data_variables.values():
            if var.has_time and DEFAULT_TIME_DIM not in dims:
                # The writer's time dimension is always called "time": the topology writer and
                # `write_ugrid_data_variable` both address it by that name, so a variable
                # whose own axis is named otherwise is written against this one. See
                # `_write_time_coordinate` for what that means for the coordinate.
                time_dim = rg.CreateDimension(
                    DEFAULT_TIME_DIM, None, None, var.n_time_steps
                )
                dims[DEFAULT_TIME_DIM] = time_dim
            # `load_array` reads each variable without memoising it on the shared dataset, so the
            # write streams one variable at a time instead of holding the whole cube resident (#982).
            write_ugrid_data_variable(
                rg, var.with_data(var.load_array()), mesh_name, dims
            )

        # Write the CF time coordinate beside its dimension, so a round trip keeps the stamps
        # the reader decoded instead of dropping them to positional indices (issue #1381).
        _write_time_coordinate(rg, dims, self._data_variables)

        global_attrs = dict(self._global_attributes)
        if "Conventions" not in global_attrs:
            global_attrs["Conventions"] = UGRID_CONVENTIONS
        write_global_attributes(rg, global_attrs)

        ds = None

    def _write_through_driver(
        self, path: str | Path, driver: str, options: dict[str, Any]
    ) -> None:
        """Write through a registered third-party driver.

        Args:
            path: Output file path.
            driver: Name of the driver to write with.
            options: Format-specific settings, passed to the driver uninterpreted.

        Raises:
            DriverNotExistError: If the driver is not installed.
            UnsupportedMeshFormatError: If the driver cannot write a mesh, or raised.
        """
        if driver.strip().lower() in RESERVED_NAMES:
            self._write_ugrid_netcdf(Path(path))
            return
        installed = mesh_drivers()
        if driver not in installed:
            raise DriverNotExistError(_unknown_driver_message(driver))
        selected = installed[driver]
        if "write_mesh" not in selected.capabilities:
            can_do = ", ".join(sorted(selected.capabilities))
            raise UnsupportedMeshFormatError(
                f"The {driver!r} driver cannot write a mesh; it declares: {can_do}."
            )
        try:
            selected.write(self, str(path), **options)
        except (UnsupportedMeshFormatError, DriverNotExistError, OSError):
            raise
        except Exception as error:
            raise UnsupportedMeshFormatError(
                f"The {driver!r} driver failed to write {str(path)!r}: {error!r}"
            ) from error

        # Warned after the write, not before: a failed write previously still reported that
        # variables "will not be in" a file that was never created.
        if "write_data" not in selected.capabilities and self._data_variables:
            warnings.warn(
                f"The {driver!r} driver wrote a mesh frame but no data; "
                f"{len(self._data_variables)} variable(s) are not in {str(path)!r}.",
                RuntimeWarning,
                stacklevel=4,
            )

    def to_geodataframe(
        self,
        variable_name: str | None = None,
        location: str = "face",
    ) -> gpd.GeoDataFrame:
        """Convert mesh to a GeoDataFrame.

        For faces: each row is a Polygon with data columns.
        For nodes: each row is a Point.
        For edges: each row is a LineString.

        Args:
            variable_name: Optional data variable to include as a column.
            location: Mesh location ("face", "node", or "edge").

        Returns:
            geopandas GeoDataFrame.
        """
        geometries = self._build_geometries(location)

        data_dict: dict[str, Any] = {}
        if variable_name is not None:
            var = self.get_data(variable_name)
            if var.location == location:
                # For a temporal variable only the first step is tabulated; `sel_time(0)` reads just
                # that slab instead of loading every step to slice `[0]` (#982). `has_data_source`
                # avoids a temporal-specific `sel_time` error for a variable with no readable data
                # (checked without forcing a load — review L3).
                if var.has_time:
                    var_data = var.sel_time(0) if var.has_data_source else None
                else:
                    var_data = var.data
                # A variable with no readable data becomes a length-correct null column rather than
                # raising — pandas rejects a scalar `None` column ("must pass an index") (review L3).
                if var_data is None:
                    var_data = np.full(len(geometries), np.nan)
                data_dict[variable_name] = var_data

        gdf = gpd.GeoDataFrame(data_dict, geometry=geometries)
        if self.crs is not None:
            gdf = gdf.set_crs(self.crs)

        result = gdf
        return result

    def _build_geometries(self, location: str) -> list:
        """Build the geometry list for a mesh location.

        Args:
            location: Mesh location ("face", "node", or "edge").

        Returns:
            List of shapely geometries — Polygons for "face", Points for
            "node", LineStrings for "edge".

        Raises:
            ValueError: If `location` is unknown, or edge connectivity is
                unavailable for an edge conversion.
        """
        if location == "face":
            geometries = MeshSpatialIndex(self._mesh).face_polygons
        elif location == "node":
            # Vectorized point construction — meshes routinely have 1e5-1e7 nodes, so a per-node
            # Python `Point(...)` loop is a hot spot (ARC-59). `list(...)` keeps the return type
            # consistent with the face/edge branches (review N2).
            geometries = list(shapely.points(self._mesh.node_x, self._mesh.node_y))
        elif location == "edge":
            if self._mesh.edge_node_connectivity is None:
                raise ValueError("Edge connectivity not available.")
            geometries = self._edge_linestrings(self._mesh.edge_node_connectivity)
        else:
            raise ValueError(f"Unknown location: {location}")
        return geometries

    def _edge_linestrings(self, enc: Connectivity) -> Any:
        """Build one LineString per edge, vectorized for standard 2-node edges (ARC-59)."""
        node_idx = np.asarray(enc.data)
        # A `None` fill means no sentinels are present, so the fast path is valid without an
        # elementwise `node_idx != None` compare (which NumPy deprecates) (review N3).
        no_fill = enc.fill_value is None or bool(np.all(node_idx != enc.fill_value))
        if node_idx.ndim == 2 and node_idx.shape[1] == 2 and no_fill:
            xs = self._mesh.node_x[node_idx]
            ys = self._mesh.node_y[node_idx]
            return list(shapely.linestrings(np.stack([xs, ys], axis=-1)))
        # Rare ragged / filled edge connectivity: fall back to a per-edge build.
        # See `Network1d._edge_linestrings`: a row with fewer than two real nodes is no
        # edge, and GEOS refuses a one-point LineString, so such a row escaped as a raw
        # GEOSException. An empty geometry keeps one row per declared edge.
        return [
            LineString(
                [
                    (self._mesh.node_x[n], self._mesh.node_y[n])
                    for n in enc.get_element(i)
                ]
            )
            if len(enc.get_element(i)) >= 2
            else LineString()
            for i in range(enc.n_elements)
        ]

    def to_feature_collection(
        self,
        variable_name: str | None = None,
        location: str = "face",
    ) -> FeatureCollection:
        """Convert mesh to a pyramids FeatureCollection.

        Args:
            variable_name: Optional data variable to include.
            location: Mesh location ("face", "node", or "edge").

        Returns:
            pyramids FeatureCollection.
        """
        gdf = self.to_geodataframe(variable_name, location)
        result = FeatureCollection(gdf)
        return result

    @classmethod
    def from_arrays(
        cls,
        node_x: np.ndarray,
        node_y: np.ndarray,
        face_node_connectivity: np.ndarray,
        data: dict[str, np.ndarray] | None = None,
        data_locations: dict[str, str] | None = None,
        epsg: int = 4326,
        mesh_name: str = DEFAULT_MESH_NAME,
    ) -> UgridDataset:
        """Create a UgridDataset programmatically from arrays.

        Plural because an unstructured mesh is not one array: the topology
        needs node coordinates *and* a face-node connectivity table before any
        data can be attached. It therefore takes a flat `epsg` rather than the
        :class:`~pyramids.base.georeference.GeoReference` the gridded
        constructors take — a mesh carries its own coordinates, so there is no
        affine transform to describe.

        Args:
            node_x: Node x-coordinates.
            node_y: Node y-coordinates.
            face_node_connectivity: (n_faces, max_nodes) array of node
                indices. Use -1 as fill value for mixed meshes.
            data: Optional dict mapping variable name to data array.
            data_locations: Optional dict mapping variable name to
                location ("face", "node", "edge"). Defaults to "face".
            epsg: EPSG code for the CRS.
            mesh_name: Name for the topology variable.

        Returns:
            UgridDataset instance.

        Examples:
            - Build the smallest possible mesh — two triangles — and inspect
              its topology:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ... )
                >>> (mesh.n_node, mesh.n_face)
                (4, 2)
                >>> mesh.bounds
                (0.0, 0.0, 1.0, 1.0)

                ```
            - Attach a per-face variable and read it back:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"depth": np.array([1.5, 2.5])},
                ... )
                >>> mesh.data_variable_names
                ['depth']
                >>> mesh["depth"].location
                'face'
                >>> mesh["depth"].data.tolist()
                [1.5, 2.5]

                ```
        """
        fnc = Connectivity(
            data=np.asarray(face_node_connectivity, dtype=np.intp),
            fill_value=-1,
            cf_role="face_node_connectivity",
            original_start_index=0,
        )
        mesh = Mesh2d(
            node_x=np.asarray(node_x, dtype=np.float64),
            node_y=np.asarray(node_y, dtype=np.float64),
            face_node_connectivity=fnc,
        )

        data_variables: dict[str, MeshVariable] = {}
        topo_data_vars: dict[str, str] = {}
        if data is not None:
            if data_locations is None:
                data_locations = {}
            for name, arr in data.items():
                loc = data_locations.get(name, "face")
                topo_data_vars[name] = loc
                data_variables[name] = MeshVariable(
                    name=name,
                    location=loc,
                    mesh_name=mesh_name,
                    shape=arr.shape,
                    _data=arr,
                )

        srs = sr_from_epsg(epsg)
        crs_wkt = srs.ExportToWkt()

        topo_info = MeshTopologyInfo(
            mesh_name=mesh_name,
            topology_dimension=2,
            node_x_var=f"{mesh_name}_node_x",
            node_y_var=f"{mesh_name}_node_y",
            face_node_var=f"{mesh_name}_face_nodes",
            data_variables=topo_data_vars,
            crs_wkt=crs_wkt,
        )

        result = cls(
            mesh=mesh,
            data_variables=data_variables,
            global_attributes={"Conventions": UGRID_CONVENTIONS},
            topology_info=topo_info,
            crs_wkt=crs_wkt,
        )
        return result

    @classmethod
    def from_structured(
        cls,
        dataset: Any,
        band_names: list[str] | None = None,
        mesh_name: str = DEFAULT_MESH_NAME,
    ) -> UgridDataset:
        """Build a mesh from a raster, one quad face per cell.

        The bridge from the structured world: each cell becomes a quad over the corner
        lattice (shared corners deduplicated) and each band becomes a per-face variable, so a
        raster can be fed to the mesh operations.

        Args:
            dataset: The source raster (a pyramids ``Dataset`` / ``NetCDF`` variable).
            band_names: Names for the per-face variables, one per band. Defaults to
                ``band_1``, ``band_2``, ….
            mesh_name: The topology name to stamp. Defaults to the package default.

        Returns:
            UgridDataset: The quad mesh carrying the band values.
        """
        node_x, node_y, faces, data = _construct.from_structured(dataset, band_names)
        return cls.from_arrays(
            node_x,
            node_y,
            faces,
            data=data,
            epsg=dataset.epsg,
            mesh_name=mesh_name,
        )

    @classmethod
    def from_geodataframe(
        cls, gdf: Any, mesh_name: str = DEFAULT_MESH_NAME
    ) -> UgridDataset:
        """Build a mesh from polygon geometries, one face per polygon.

        Vertices are deduplicated into the node set and each ring is oriented
        counter-clockwise; the frame's attribute columns become per-face variables.

        Args:
            gdf: A GeoDataFrame of polygons. Its ``crs`` is carried onto the mesh verbatim,
                so a projected CRS stays projected even when it has no EPSG code.
            mesh_name: The topology name to stamp. Defaults to the package default.

        Returns:
            UgridDataset: The mesh built from the polygons.

        Raises:
            ValueError: The frame declares no CRS, so the mesh would carry no
                georeferencing.
        """
        node_x, node_y, faces, data = _construct.from_geodataframe(gdf)
        # Carry the frame's own CRS. Reading an EPSG code and defaulting to 4326 stamped degrees
        # on a projected frame whose CRS has no EPSG code, and on a frame with no CRS at all --
        # silent georeferencing corruption, since everything downstream trusts `epsg`.
        crs = getattr(gdf, "crs", None)
        if crs is None:
            raise ValueError(
                "from_geodataframe: the GeoDataFrame declares no CRS, so the mesh would have no "
                "georeferencing. Set `gdf.crs` (e.g. gdf.set_crs(4326)) before converting."
            )
        epsg = crs.to_epsg()
        built = cls.from_arrays(
            node_x,
            node_y,
            faces,
            data=data,
            epsg=epsg if epsg is not None else 4326,
            mesh_name=mesh_name,
        )
        if epsg is not None:
            return built
        # A CRS with no EPSG code (a projected one given as WKT, say) would otherwise be
        # reduced to the 4326 placeholder `from_arrays` needs, stamping degrees on metres.
        # Keep the frame's WKT verbatim instead.
        wkt = crs.to_wkt()
        return cls(
            mesh=built.mesh,
            data_variables=built.data_vars,
            global_attributes={"Conventions": UGRID_CONVENTIONS},
            topology_info=_topology_info_named(mesh_name, crs_wkt=wkt),
            crs_wkt=wkt,
            file_name=None,
        )

    @classmethod
    def from_xarray(cls, ds: Any) -> UgridDataset:
        """Read a mesh back from an ``xarray.Dataset`` in the UGRID-CF encoding.

        The inverse of :meth:`to_xarray`. xarray is a peer dependency, imported only inside
        the bridge, so nothing in this module imports it at module scope.

        Args:
            ds: The ``xarray.Dataset`` to read.

        Returns:
            UgridDataset: The reconstructed mesh and variables.

        Raises:
            OptionalPackageDoesNotExist: xarray is not installed.
        """
        mesh, data_variables = _interop.from_xarray(ds)
        mesh_name = _interop.read_mesh_name(ds)
        return cls(
            mesh=mesh,
            data_variables=data_variables,
            global_attributes={},
            # Keep the topology's own name: without it a mesh called anything other than
            # "mesh2d" came back renamed, and a re-export then wrote the wrong dimensions.
            topology_info=_topology_info_named(mesh_name),
            crs_wkt=_interop.read_crs_wkt(ds),
            file_name=None,
            # Rebuild the ragged volume topology from its companion arrays when present
            # (issue #1330); `None` for a 2-D / uniform mesh, leaving the dense path in force.
            volume_topology=_interop.volume_topology_from_xarray(ds),
        )

    @classmethod
    def from_zarr(cls, store: Any, **kwargs: Any) -> UgridDataset:
        """Read a mesh from a zarr store written by :meth:`to_zarr`.

        Args:
            store: The zarr store (a path or a mapping).
            **kwargs: Passed to ``xarray.open_zarr``.

        Returns:
            UgridDataset: The reconstructed mesh and variables.

        Raises:
            OptionalPackageDoesNotExist: xarray or zarr is not installed.
        """
        # One open, read twice: the mesh and the CRS both come off the same dataset, so the
        # store is not opened again just to recover the grid mapping.
        opened = _interop.open_zarr_dataset(store, **kwargs)
        mesh, data_variables = _interop.from_xarray(opened)
        return cls(
            mesh=mesh,
            data_variables=data_variables,
            global_attributes={},
            topology_info=_topology_info_named(_interop.read_mesh_name(opened)),
            crs_wkt=_interop.read_crs_wkt(opened),
            file_name=None,
        )

    @staticmethod
    def mesh_names(path: str | Path, driver: str | None = None) -> list[str]:
        """The names of every topology a file declares.

        A mesh file may carry several topologies; :meth:`read_file` takes the first unless told
        otherwise, so this is how a caller discovers what else is in there.

        Dispatch mirrors :meth:`read_file` exactly, including the short-circuit that keeps a
        NetCDF suffix from triggering driver discovery. Every driver is asked, not only those
        declaring ``multi_mesh``: a single-mesh format answers with a one-item list, which is
        the right answer rather than an error.

        Args:
            path: Path to the file.
            driver: Name of a registered driver to ask, bypassing detection. ``None`` (the
                default) resolves as described above.

        Returns:
            list[str]: One name per declared topology, in file order.

        Raises:
            FileNotFoundError: The file does not exist.
            DriverNotExistError: ``driver`` names a driver that is not installed.
            UnsupportedMeshFormatError: No installed driver claims the suffix and the
                built-in reader cannot open it either, or a driver failed or returned
                something other than a list of topology names.
            IsADirectoryError: The path is a directory that no driver claims.
            RuntimeError: GDAL cannot open a file that reached the built-in reader by its own
                suffix. GDAL exceptions are enabled package-wide, so the open failure
                surfaces as GDAL's own error.
            ValueError: The file declares no UGRID topology.
        """
        selected, native = _resolve_read_driver(path, driver)
        if selected is not None:
            result = _mesh_names_through_driver(selected, path)
        else:
            try:
                result = UgridDataset._ugrid_netcdf_mesh_names(
                    path, wrap_unreadable=not native
                )
            except NoMeshTopologyError:
                fallback = _netcdf_fallback_driver(path, driver)
                if fallback is None:
                    raise
                result = _mesh_names_through_driver(fallback, path)
        return result

    @staticmethod
    def _ugrid_netcdf_mesh_names(
        path: str | Path, wrap_unreadable: bool = False
    ) -> list[str]:
        """List the topology names in a UGRID NetCDF file.

        Args:
            path: Path to the ``.nc`` file.
            wrap_unreadable: True when this call is the fallback for a suffix no driver
                claimed, so a failure reports the installed drivers rather than GDAL's
                "not recognized" — the same treatment :meth:`read_file` gives it.

        Returns:
            list[str]: One name per declared topology, in file order.

        Raises:
            FileNotFoundError: The file does not exist.
            UnsupportedMeshFormatError: GDAL cannot open a file that reached here as a
                fallback from driver detection.
            ValueError: The file declares no UGRID topology.
        """
        target = str(path)
        if not target.startswith("/vsi"):
            resolved = Path(path)
            if not resolved.exists():
                raise FileNotFoundError(
                    f"File not found: {Path(resolved)}"
                )  # pragma: no cover - `_require_existing_file` runs first on every public route
            target = str(resolved)
        # See `read_file`: with GDAL exceptions on an unopenable file raises RuntimeError,
        # but that setting is process-global and reversible, so the guard stays.
        try:
            dataset = gdal.OpenEx(
                target, gdal.OF_MULTIDIM_RASTER | gdal.OF_VERBOSE_ERROR
            )
        except RuntimeError as error:
            if not wrap_unreadable:
                raise
            if not target.startswith("/vsi") and Path(target).is_dir():
                raise IsADirectoryError(
                    f"Not a mesh file: {target} is a directory."
                ) from error
            suffix = "" if target.startswith("/vsi") else Path(target).suffix
            raise UnsupportedMeshFormatError(
                unsupported_format_message(str(path), suffix)
            ) from error
        if (
            dataset is None
        ):  # pragma: no cover - needs gdal.DontUseExceptions() process-wide
            raise ValueError(f"GDAL cannot open file: {path}")
        rg = dataset.GetRootGroup()
        if rg is None:  # pragma: no cover - no multidim driver answers None here
            # Kept as a clear message rather than letting `parse_ugrid_topology(None)`
            # raise an AttributeError, though every multidim driver that opens a file
            # does expose a root group.
            raise ValueError(f"Cannot get root group from: {path}")
        topologies = parse_ugrid_topology(rg)
        if not topologies:
            raise NoMeshTopologyError(f"No UGRID mesh topology found in: {path}")
        return [topo.mesh_name for topo in topologies]

    @classmethod
    def open_mfdataset(
        cls,
        paths: str | Path | Sequence[str | Path],
        *,
        driver: str | None = None,
        mesh_name: str | None = None,
        sort: bool = True,
    ) -> UgridDataset:
        """Open many mesh files sharing one topology and stack them along time (#1378).

        The many-**files** entry point. :meth:`read_all` answers every topology in **one**
        file; this answers one topology across many files, which is the shape a long run is
        written in — one file per day, per month, or per restart.

        The topology is read from the first file and every other file must match it; the data
        variables are concatenated along time by :meth:`concat`, so the rules about what may
        be joined are that method's rules, stated in one place.

        Args:
            paths: A glob pattern (``"out/*_map.nc"``), a single path, or a sequence of paths.
                A pattern that matches nothing is an error rather than an empty dataset.
            driver: Name of a registered mesh driver, bypassing detection. ``None`` detects.
            mesh_name: Which topology to take from each file. ``None`` takes the first.
            sort: Order the files by their first time stamp before stacking, so a run whose
                filenames do not sort chronologically still comes back in time order —
                ``run_t10`` sorts before ``run_t2`` lexically, which a glob would otherwise
                stack in that order.
                Only a **dated** axis can be ordered this way. A file carrying no CF time
                units reports positional indices, which say nothing about where it belongs, so
                it keeps its given position even with ``sort=True``: for a set of undated
                files, pass an explicitly ordered sequence rather than a glob. In a mixed set
                the dated files are ordered among themselves and placed back into the slots
                they occupied, so the undated ones do not move.
                ``False`` always keeps the given order.

        Returns:
            UgridDataset: One dataset on the shared topology, its time axis spanning every
            file in order.

        Raises:
            ValueError: ``paths`` is empty, or a glob pattern matches nothing.
            AlignmentError: A file sits on a different topology than the first.

        See Also:
            read_all: Every topology within one file.
            concat: The time-axis join this performs, and its rules.

        Examples:
            - Stack a run written one file per day:
                ```python
                >>> ds = UgridDataset.open_mfdataset("out/*_map.nc")  # doctest: +SKIP
                >>> ds.time_values[0], ds.time_values[-1]  # doctest: +SKIP
                ```
        """
        if isinstance(paths, (str, Path)):
            pattern = str(paths)
            is_pattern = any(character in pattern for character in "*?[")
            matched = sorted(glob(pattern)) if is_pattern else []
            if matched:
                resolved: list[str | Path] = list(matched)
            elif is_pattern:
                raise ValueError(
                    f"open_mfdataset() got the pattern {pattern!r}, which matches no file."
                )
            else:
                resolved = [paths]
        else:
            resolved = list(paths)
        if not resolved:
            raise ValueError(
                "open_mfdataset() got an empty list of paths; there is nothing to open."
            )
        datasets = [
            cls.read_file(path, driver=driver, mesh_name=mesh_name) for path in resolved
        ]
        if sort:
            # A run's filenames need not sort chronologically (`run_t10` sorts before
            # `run_t2`), so order by what the data says instead. Only a *dated* axis can be
            # ordered: a file carrying no CF time units reports positional indices, which say
            # nothing about where it belongs.
            #
            # So the dated files are sorted *among themselves* and dropped back into the slots
            # they occupied, leaving every undated file exactly where it was given. Sorting the
            # whole list with undated files pushed to one end would move them, which is what
            # this method's own docstring promises not to do.
            dated_slots = [
                index
                for index, dataset in enumerate(datasets)
                if dataset.time_values
                and any(
                    TIME_UNITS_ATTR in var.attributes
                    for var in dataset._data_variables.values()
                )
            ]

            def first_stamp(dataset: UgridDataset) -> tuple:
                """The sort key of a dated dataset: its earliest stamp."""
                stamps = dataset.time_values
                # `dated_slots` holds only datasets whose `time_values` is non-empty, which
                # the type checker cannot see from the comprehension above.
                assert stamps is not None
                return _stamp_order(stamps[0])

            ordered = sorted(
                (datasets[index] for index in dated_slots), key=first_stamp
            )
            for slot, dataset in zip(dated_slots, ordered, strict=True):
                datasets[slot] = dataset
        head, *rest = datasets
        return head.concat(rest) if rest else head

    @classmethod
    def read_all(
        cls, path: str | Path, driver: str | None = None, lazy: bool = True
    ) -> dict[str, UgridDataset]:
        """Read **every** topology in a file, one dataset each.

        :meth:`read_file` answers a single mesh (the first, or the one named). This answers
        all of them, so nothing in a multi-mesh file is silently dropped. Dispatch follows
        :meth:`mesh_names` and :meth:`read_file`, so a third-party format works here too.

        Args:
            path: Path to the file.
            driver: Name of a registered **mesh** driver to use, bypassing detection.
                ``None`` (the default) detects.
            lazy: Defer reading variable values until first access. Forwarded to a driver,
                which may honour an eager read; the built-in UGRID reader has no eager mode, so
                ``lazy=False`` on a native read raises :class:`TypeError`, exactly as
                :meth:`read_file` does. Without it a multi-topology third-party format could
                only ever be read lazily.

        Returns:
            dict[str, UgridDataset]: Each topology name mapped to its dataset.

        Raises:
            FileNotFoundError: The file does not exist.
            DriverNotExistError: ``driver`` names a driver that is not installed.
            UnsupportedMeshFormatError: No installed driver reads the file and the built-in
                reader cannot either — raised from :meth:`mesh_names`, which this delegates
                to, so every error that method raises surfaces here too.
            IsADirectoryError: The path is a directory that no driver claims.
            RuntimeError: GDAL cannot open a file that reached the built-in reader by its own
                suffix. GDAL exceptions are enabled package-wide, so the open failure
                surfaces as GDAL's own error.
            TypeError: ``lazy=False`` on a native (built-in UGRID) read, which has no eager
                mode -- the same rejection :meth:`read_file` makes.
            ValueError: The file declares no UGRID topology.
        """
        # Resolve once, for real. Passing a driver *name* through only short-circuited the
        # route where detection had found something: when nothing claimed the suffix the name
        # was None, so `mesh_names` and every per-topology read re-ran full detection anyway
        # -- measured at two `can_open` calls for one `read_all`, growing per topology.
        # Threading the resolved object through covers the fallback route too.
        selected, native = _resolve_read_driver(path, driver)
        # Set in the native branch below; stays empty whenever a driver handles the file --
        # resolved up front, or picked by the fallback -- in which case it is never read.
        native_names: list[str] = []
        if selected is None:
            try:
                native_names = cls._ugrid_netcdf_mesh_names(
                    path, wrap_unreadable=not native
                )
            except NoMeshTopologyError:
                # The file opened as NetCDF but declares no UGRID topology; fall back to a
                # driver claiming the suffix, as read_file does. If none claims it, the
                # original error stands.
                selected = _netcdf_fallback_driver(path, driver)
                if selected is None:
                    raise
        if selected is None:
            result = {
                name: cls._read_ugrid_netcdf(
                    path, name, wrap_unreadable=not native, lazy=lazy
                )
                for name in native_names
            }
        else:
            names = _mesh_names_through_driver(selected, path)
            result = {
                name: _read_through_driver(selected, path, name, cls, lazy)
                for name in names
            }
        return result

    def _layer_axis(self, var: MeshVariable) -> int | None:
        """The axis holding the layer dimension, or ``None`` when the variable has none.

        A mesh variable's axes read ``[time?, layer?, element]`` — the element axis is the
        last and time is whichever :attr:`MeshVariable.time_index` names, so a remaining
        middle axis is the layer. A 2-D variable whose dimension names mark it non-temporal
        is therefore ``(layer, element)`` with layer axis 0.

        Two cases answer ``None`` rather than guessing. A variable carrying no dimension
        names at all (an array-built one) falls back to "the leading axis of a >1-D array is
        time", so its 2-D form reads as ``(time, element)``; name the dimensions to have it
        read as layers. And a variable whose time dimension is *last* contradicts the layout
        above — the element axis is supposed to be last — so no axis can be claimed as the
        layer axis without mistaking the element axis for it.

        Args:
            var: The variable to inspect.

        Returns:
            int | None: The layer axis, or ``None``.
        """
        if not var.has_data_source:
            return None
        # The declared shape, not `var.data`: touching the data fires the lazy loader and
        # pulls every variable off disk just to learn how many axes it has -- the same defect
        # `info()` carried.
        rank = len(var.shape)
        if rank < 2:
            return None
        if var.time_index == rank - 1:
            # Time sits where the element axis belongs, so the layout is not one we can read.
            return None
        axes = [axis for axis in range(rank - 1) if axis != var.time_index]
        return axes[0] if axes else None

    @property
    def volume_topology(self) -> VolumeTopology | None:
        """The ragged (per-column) vertical layering, or ``None`` for a uniform / 2-D mesh.

        Present only for a genuinely 3-D mesh whose columns carry different layer counts
        (issue #1330): it maps each face to its slice of the flat ``volume`` axis that a
        ``location="volume"`` variable is indexed through. ``None`` means the dense
        ``(layer, element)`` path applies — the uniform-layer behaviour is unchanged.
        """
        return self._volume_topology

    @property
    def n_volume(self) -> int | None:
        """The total number of volumes, or ``None`` when the mesh has no volume topology.

        The flat ``volume``-axis length of a ragged 3-D mesh (the sum of every column's layer
        count). ``None`` for a 2-D or uniform-layer mesh, where :attr:`n_layers` applies
        instead.
        """
        return None if self._volume_topology is None else self._volume_topology.n_volume

    @property
    def n_layers(self) -> int | None:
        """The number of layers, or ``None`` when no variable is layered.

        A 3-D mesh output puts some variables on the ``n`` layer centres and others on the
        ``n + 1`` layer interfaces, so two counts differing by one is normal rather than a
        contradiction; this reports ``n``, the layer count proper. Any other disagreement is
        a real inconsistency and raises. :meth:`isel_layer` is unaffected either way — it
        indexes each variable on its own layer axis.

        Reporting ``n`` means the ``n + 1`` is not visible here, so a caller iterating
        ``range(n_layers)`` over an interface variable would skip its last interface. Read
        :attr:`n_layer_interfaces` for that count rather than inferring it: it answers ``None``
        unless a variable really sits on the interfaces.

        For a **ragged** 3-D mesh (:attr:`volume_topology` set) there is no single layer count:
        this reports the **maximum** over the columns — the number of layer *slots* — so
        ``range(n_layers)`` covers the deepest column, and :meth:`isel_layer` makes the absent
        shallow-column layers explicit (NaN) rather than padding them silently.

        Returns:
            int | None: The layer-centre count (the max, for a ragged mesh), or ``None`` when
            no variable is layered.

        Raises:
            ValueError: The layered variables carry counts that are not a layer-centre /
                layer-interface pair.
        """
        if self._volume_topology is not None:
            return self._volume_topology.max_layers
        counts = self._layer_counts()
        return min(counts) if counts else None

    @property
    def n_layer_interfaces(self) -> int | None:
        """The number of layer interfaces, or ``None`` when nothing sits on them.

        The companion to :attr:`n_layers`. A 3-D output's vertical velocities and fluxes live on
        the ``n + 1`` interfaces between the ``n`` layer centres, and ``n_layers`` deliberately
        reports the centre count -- so this is where the other half of the pair is readable.

        It is **not** simply ``n_layers + 1``, which is always computable: that would assert
        that something in the dataset is interface-located. Only a variable actually carrying
        that count makes it true, so a centres-only dataset answers ``None``.

        Returns:
            int | None: The layer-interface count, or ``None`` when no variable is layered or
            every layered variable sits on the centres.

        Raises:
            ValueError: The layered variables carry counts that are not a layer-centre /
                layer-interface pair -- the same guard :attr:`n_layers` applies, so the two
                properties agree about what is readable.
        """
        counts = self._layer_counts()
        if not counts:
            return None
        interfaces = min(counts) + 1
        return interfaces if interfaces in counts else None

    def _layer_counts(self) -> set[int]:
        """The distinct layer counts across the layered variables, validated.

        Returns:
            set[int]: One entry per distinct count, empty when no variable is layered.

        Raises:
            ValueError: The counts are not a single value or a layer-centre / layer-interface
                pair. The test is ``counts - {smallest, smallest + 1}`` rather than "every gap
                is 1", so ``{20, 21, 22}`` is refused too: a mesh cannot have both 21 and 22
                interfaces for 20 centres.
        """
        counts = set()
        for var in self._data_variables.values():
            axis = self._layer_axis(var)
            if axis is not None:
                counts.add(int(var.shape[axis]))
        smallest = min(counts) if counts else 0
        if counts - {smallest, smallest + 1}:
            raise ValueError(
                f"layered variables disagree on their layer count: {sorted(counts)}."
            )
        return counts

    @property
    def layer_values(self) -> list | None:
        """The layer coordinate values, when a layered variable carries them.

        Read from a layered variable's ``layer_values`` attribute. The UGRID reader does not
        populate that attribute -- as with :attr:`time_values`, the coordinate is supplied by
        whoever builds or transforms the dataset -- so this is normally ``None`` for a mesh
        read straight from a file, and :meth:`sel_layer` then selects by layer position.
        """
        for var in self._data_variables.values():
            if self._layer_axis(var) is not None:
                stamps = var.attributes.get("layer_values")
                if stamps is not None:
                    return list(stamps)
        return None

    def isel_layer(self, index: int | slice | list[int] | np.ndarray) -> UgridDataset:
        """Select along the layer axis by position.

        A layered variable — ``(layer, element)``, or ``(time, layer, element)`` — is indexed
        on its layer axis. An integer collapses that axis (the variable loses its layer
        dimension); a slice or sequence keeps it, trimmed. Variables with no layer axis are
        carried through untouched, as the time selectors carry static variables.

        For a **ragged** 3-D mesh (:attr:`volume_topology` set) a ``location="volume"``
        variable has no rectangular layer axis to index; the selection is per column instead.
        ``index`` must be an ``int`` ``k``: each column yields its ``k``-th layer where it has
        one, and a column shallower than ``k + 1`` layers yields NaN — the absent layers are
        made explicit, never padded silently. The volume variable becomes a plain
        ``location="face"`` field; other variables carry through as on the uniform path.

        Args:
            index: An ``int`` layer, a ``slice``, or a sequence of layer positions. A ragged
                mesh accepts only an ``int``.

        Returns:
            UgridDataset: A new dataset with the layer selection applied.

        Raises:
            ValueError: No variable has a layer dimension, or a non-``int`` ``index`` was given
                for a ragged mesh.
        """
        if self._volume_topology is not None:
            return self._isel_layer_ragged(index)
        new_vars: dict[str, MeshVariable] = {}
        layered = False
        for name, var in self._data_variables.items():
            axis = self._layer_axis(var)
            if axis is None:
                new_vars[name] = var
                continue
            layered = True
            data = np.asarray(var.data)
            if isinstance(index, (int, np.integer)):
                picked = np.take(data, int(index), axis=axis)
                moved = var.with_data(picked)
                moved.dimensions = tuple(
                    dim
                    for position, dim in enumerate(var.dimensions)
                    if position != axis
                )
            else:
                positions = (
                    np.arange(data.shape[axis])[index]
                    if isinstance(index, slice)
                    else np.asarray(index, dtype=np.intp)
                )
                moved = var.with_data(np.take(data, positions, axis=axis))
            new_vars[name] = moved
        if not layered:
            raise ValueError(
                "isel_layer needs at least one variable with a layer dimension; this "
                "dataset has none."
            )
        return self._rebuild(new_vars)

    def sel_layer(self, value: Any) -> UgridDataset:
        """Select along the layer axis by coordinate value.

        Matches ``value`` against :attr:`layer_values`, falling back to layer positions when
        no layer coordinate is present -- which is the usual case, since the reader does not
        populate `layer_values` (see :attr:`layer_values`). So on a mesh read from a file,
        ``sel_layer(1)`` selects layer position 1.

        Args:
            value: The layer coordinate value to select.

        Returns:
            UgridDataset: A new dataset with that layer selected.

        Raises:
            ValueError: No layer dimension, or the value is not among the layer coordinates.
        """
        count = self.n_layers
        if count is None:
            raise ValueError(
                "sel_layer needs at least one variable with a layer dimension; this "
                "dataset has none."
            )
        # Read the property once: it walks every variable, so evaluating it twice walked
        # them twice.
        stored = self.layer_values
        coords = stored if stored is not None else list(range(count))
        if value not in coords:
            raise ValueError(
                f"sel_layer: layer value {value!r} not found in the layer coordinate "
                f"{coords!r}."
            )
        return self.isel_layer(coords.index(value))

    def _isel_layer_ragged(
        self, index: int | slice | list[int] | np.ndarray
    ) -> UgridDataset:
        """Select the ``index``-th layer per column for a ragged 3-D mesh (issue #1330).

        The per-column counterpart of :meth:`isel_layer`: a ``location="volume"`` variable's
        flat ``(time?, n_volume)`` data is gathered to a ``(time?, n_face)`` face field, each
        column contributing its ``index``-th volume where it has one and NaN where it does not,
        so the shallow columns' absent layers are explicit rather than padded. Non-volume
        variables are carried through untouched.

        Args:
            index: The 0-based layer position to take from every column. Only an ``int`` is
                meaningful for a ragged mesh.

        Returns:
            UgridDataset: A new dataset with the volume variables collapsed to face fields.

        Raises:
            ValueError: ``index`` is not an ``int``, or is negative.
        """
        if not isinstance(index, (int, np.integer)):
            raise ValueError(
                "isel_layer on a ragged (volume) mesh needs an int layer position; a slice "
                "or sequence is ambiguous when columns have different layer counts. Select "
                "one layer at a time."
            )
        if int(index) < 0:
            # A negative layer would make every column "valid" (`layer_count > -1`) and index
            # `volume_offset + layer` with a negative offset, wrapping into the previous
            # column's volumes — garbage, not a per-column top layer. Reject it, matching
            # VolumeTopology.volume_index, which guards negatives too (review L1).
            raise ValueError(
                f"isel_layer on a ragged (volume) mesh needs a non-negative layer position; "
                f"got {int(index)}. A column's top layer varies by column, so there is no "
                f"well-defined negative index."
            )
        topology = cast("VolumeTopology", self._volume_topology)
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if var.location != "volume":
                new_vars[name] = var
                continue
            new_vars[name] = self._gather_layer_from_volume(var, int(index), topology)
        return self._rebuild_without_volume(new_vars)

    def _gather_layer_from_volume(
        self, var: MeshVariable, layer: int, topology: VolumeTopology
    ) -> MeshVariable:
        """Collapse one ragged ``volume`` variable to a ``(time?, n_face)`` face field.

        Face ``f`` takes volume ``volume_offset[f] + layer`` when ``layer < layer_count[f]``,
        else NaN. Vectorised: the valid faces gather in one fancy-index, the rest are left NaN.

        Args:
            var: The ``location="volume"`` variable (flat ``(time?, n_volume)`` data).
            layer: The 0-based layer position to take from each column.
            topology: The mesh's volume topology.

        Returns:
            MeshVariable: A ``location="face"`` variable of shape ``(time?, n_face)``.
        """
        data = np.asarray(var.data, dtype="float64")
        n_face = topology.n_face
        valid = topology.layer_count > layer
        volume_positions = topology.volume_offset[:-1][valid] + layer
        out_shape = (*data.shape[:-1], n_face)
        out = np.full(out_shape, np.nan, dtype="float64")
        out[..., valid] = data[..., volume_positions]
        # Drop the flat `volume` dimension name for the face dimension; keep a leading time
        # dimension name when the variable had one.
        if var.dimensions:
            new_dims = (*var.dimensions[:-1], f"{var.mesh_name}_nFaces")
        else:
            new_dims = ()
        return MeshVariable(
            name=var.name,
            location="face",
            mesh_name=var.mesh_name,
            shape=out.shape,
            attributes=dict(var.attributes),
            nodata=var.nodata,
            units=var.units,
            standard_name=var.standard_name,
            dimensions=new_dims,
            _data=out,
        )

    def _rebuild_without_volume(
        self, data_variables: dict[str, MeshVariable]
    ) -> UgridDataset:
        """A :meth:`_rebuild` that drops the volume topology — the layer axis is gone.

        Used by the ragged layer selectors: once a ``volume`` variable has been gathered to a
        face field, the result is an ordinary 2-D dataset and must not keep a volume topology
        that no variable is indexed through any more.
        """
        return type(self)(
            mesh=self._mesh,
            data_variables=data_variables,
            global_attributes=self._global_attributes,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
        )

    def collapse_layer(self, layer: int, *, location: str = "face") -> UgridDataset:
        """Collapse a ragged 3-D mesh's ``volume`` variables to a 2-D field (issue #1330).

        The explicit 2-D collapse of a ragged mesh: each column's ``layer``-th value becomes a
        plain ``(n_face,)`` (or ``(time, n_face)``) face field, absent layers NaN. It is
        :meth:`isel_layer` under a name that says "give me a 2-D slice", so a caller can ask for
        the surface/bed layer as a flat field without reaching for the per-column internals.
        (Named ``collapse_layer`` rather than ``to_location`` because the latter already moves a
        variable *between* mesh locations by graph interpolation — a different operation.)

        Args:
            layer: The 0-based layer position to take from each column.
            location: The target mesh location. Only ``"face"`` is supported — a ragged volume
                collapses onto its columns' faces. Defaults to ``"face"``.

        Returns:
            UgridDataset: A new dataset whose volume variables are 2-D face fields.

        Raises:
            ValueError: ``location`` is not ``"face"``, or the dataset has no volume topology
                to collapse.
        """
        if self._volume_topology is None:
            raise ValueError(
                "collapse_layer needs a ragged volume topology; this dataset has none (it is "
                "2-D or uniformly layered). Use isel_layer for a uniform mesh."
            )
        if location != "face":
            raise ValueError(
                f"collapse_layer supports only 'face' for a ragged volume mesh, not "
                f"{location!r}."
            )
        return self._isel_layer_ragged(int(layer))

    def to_dataframe(
        self, variables: Sequence[str] | None = None, *, dropna: bool = False
    ) -> pd.DataFrame:
        """A tidy frame of the mesh values, one row per element (and step).

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.to_dataframe`, in the **tidy**
        shape rather than the raster ``(y, x)`` MultiIndex one: an unstructured element has no
        row/column address, so each row carries the element index, its centroid coordinates,
        the time step where the variable has one, and the value.

        Args:
            variables: Which data variables to include. ``None`` (the default) takes them all.
            dropna: Drop rows whose value is no-data. Defaults to False.

        Returns:
            pandas.DataFrame: Columns ``variable``, ``element``, ``x``, ``y``, ``layer``,
            ``time`` and ``value``. ``element`` indexes the facet the variable sits on and
            ``x``/``y`` are that facet's coordinates, so a node variable is addressed by node.
            ``layer`` is the layer coordinate, or None for an unlayered variable, and ``time``
            the step coordinate, or None for a static one.

        Raises:
            KeyError: A requested variable is not a data variable of this dataset.
        """
        names = list(self._data_variables) if variables is None else list(variables)
        frames: list[pd.DataFrame] = []
        for name in names:
            if name not in self._data_variables:
                raise KeyError(name)
            var = self._data_variables[name]
            if var.data is None:
                continue
            frames.extend(self._variable_frames(name, var))
        if not frames:
            # Match the populated frame's dtypes, so a caller that concatenates or
            # dtype-checks sees one schema either way.
            return pd.DataFrame(
                {
                    "variable": pd.Series(dtype="str"),
                    "element": pd.Series(dtype="int64"),
                    "x": pd.Series(dtype="float64"),
                    "y": pd.Series(dtype="float64"),
                    "layer": pd.Series(dtype="object"),
                    "time": pd.Series(dtype="object"),
                    "value": pd.Series(dtype="float64"),
                }
            )
        frame = pd.concat(frames, ignore_index=True)
        if dropna:
            frame = frame[~frame["value"].isna()].reset_index(drop=True)
        return frame

    def _variable_frames(self, name: str, var: MeshVariable) -> list[pd.DataFrame]:
        """One tidy block per (time step, layer) of a single variable.

        Args:
            name: The variable's name, carried into the ``variable`` column.
            var: The variable to lay out.

        Returns:
            list: The blocks, in time-then-layer order.
        """
        if var.location == "volume" and self._volume_topology is not None:
            # A ragged volume variable is flat `(time?, n_volume)`: lay it out one row per
            # volume, carrying the column (`element`) and the layer position within it rather
            # than fabricating rows for the absent layers of shallow columns (issue #1330).
            return self._volume_variable_frames(name, var)
        raw = np.asarray(var.data)
        # Gap-masking casts to float64, which a classified / label field cannot survive --
        # and such a field carries no no-data value to mask anyway.
        values = (
            gaps_as_nan(raw, var.nodata) if np.issubdtype(raw.dtype, np.number) else raw
        )
        # Address the rows with the coordinates of the facet the variable actually sits on. Using
        # face centroids for every variable left a node- or edge-located one with a NaN
        # coordinate on every row, since its value count is n_node / n_edge.
        coords = self._element_coords(var.location)
        arranged, steps, layer_labels, temporal, layered = self._arrange_for_rows(
            var, values
        )
        blocks: list[pd.DataFrame] = []
        for step_position, step in enumerate(steps):
            per_step = arranged[step_position] if temporal else arranged
            for layer_position, layer in enumerate(layer_labels):
                slab = per_step[layer_position] if layered else per_step
                blocks.append(
                    self._tidy_rows(name, np.asarray(slab), coords, step, layer)
                )
        return blocks

    def _volume_variable_frames(
        self, name: str, var: MeshVariable
    ) -> list[pd.DataFrame]:
        """Tidy blocks for a ragged ``volume`` variable — one row per volume (issue #1330).

        Each row carries the column (``element`` = the face the volume belongs to), the
        0-based ``layer`` within that column, the face's ``x``/``y`` centroid, and the value.
        A temporal variable emits one block per step; a static one a single block. No row is
        emitted for an absent layer, since the flat volume axis holds only the layers that
        exist.

        Args:
            name: The variable name, carried into the ``variable`` column.
            var: The ``location="volume"`` variable.

        Returns:
            list: The per-step blocks.
        """
        topology = cast("VolumeTopology", self._volume_topology)
        raw = np.asarray(var.data)
        values = (
            gaps_as_nan(raw, var.nodata) if np.issubdtype(raw.dtype, np.number) else raw
        )
        face_of_volume = topology.face_of_volume()
        layer_of_volume = topology.layer_of_volume()
        face_coords = self._element_coords("face")
        have_coords = face_coords.shape[0] == topology.n_face
        coords = (
            face_coords[face_of_volume]
            if have_coords
            else np.full((topology.n_volume, 2), np.nan, dtype="float64")
        )
        if var.has_time:
            time_axis = cast("int", var.time_index)
            stamps = var.attributes.get("time_values")
            steps = (
                list(stamps)
                if stamps is not None
                else list(range(values.shape[time_axis]))
            )
            per_step = [np.take(values, i, axis=time_axis) for i in range(len(steps))]
        else:
            steps = [None]
            per_step = [values]
        blocks: list[pd.DataFrame] = []
        for step, slab in zip(steps, per_step):
            flat = np.asarray(slab).ravel()
            blocks.append(
                pd.DataFrame(
                    {
                        "variable": np.repeat(name, flat.shape[0]),
                        "element": face_of_volume,
                        "x": coords[:, 0],
                        "y": coords[:, 1],
                        "layer": layer_of_volume,
                        "time": np.repeat(step, flat.shape[0]),
                        "value": (
                            flat.astype("float64")
                            if np.issubdtype(flat.dtype, np.number)
                            else flat
                        ),
                    }
                )
            )
        return blocks

    def _element_axis(self, var: MeshVariable, values: np.typing.NDArray) -> int:
        """The axis of ``values`` that runs over the mesh elements.

        The element axis is conventionally last, and assuming so is what broke a variable whose
        dimension names put it first: the last axis was read as the elements, so a
        ``(n_faces, time)`` variable emitted one row per *time step*, dropping the values past
        the element count and leaving their coordinates NaN.

        The variable's declared element count decides it. The last axis is preferred when more
        than one matches -- a square variable is genuinely ambiguous, and last is the convention.

        Args:
            var: The variable, for its location and dimension names.
            values: Its values.

        Returns:
            int: The element axis. The last axis when nothing matches the element count, which
            keeps the previous behaviour for a variable whose shape says nothing.
        """
        if values.ndim < 2:
            return values.ndim - 1
        counts = {"face": self.n_face, "node": self.n_node, "edge": self.n_edge}
        expected = counts.get(var.location)
        matching = (
            [axis for axis in range(values.ndim) if values.shape[axis] == expected]
            if expected
            else []
        )
        return matching[-1] if matching else values.ndim - 1

    def _row_axes(
        self, var: MeshVariable, values: np.typing.NDArray
    ) -> tuple[int, int | None, int | None]:
        """The element, time and layer axes the tidy frame will walk.

        Resolves the three against each other and refuses anything left over, so
        :meth:`_arrange_for_rows` is left with the transpose and the labels.

        An axis can be claimed twice: `var.time_index` may name the axis that holds the
        elements. :meth:`_element_axis` settles that by the declared element count, and the
        element reading wins -- so such an axis is *not* walked as a step, and the caller is
        told which axes were.

        Args:
            var: The variable being laid out.
            values: Its values.

        Returns:
            tuple: ``(element_axis, time_axis, layer_axis)``, the last two ``None`` when there
            is no such axis to walk.

        Raises:
            ValueError: An axis is neither walked nor addressed. The tidy layout is one row per
                element with a ``time`` and a ``layer`` column, so a fourth dimension has
                nowhere to go -- and folding it into the element slot emitted ``element``
                indices past the element count with NaN coordinates, a frame a caller joins on.
        """
        element_axis = self._element_axis(var, values)
        time_axis = cast("int | None", var.time_index) if var.has_time else None
        time_axis = None if time_axis == element_axis else time_axis
        layer_axis = self._layer_axis(var)
        layer_axis = None if layer_axis == element_axis else layer_axis

        walked = {element_axis, *(a for a in (time_axis, layer_axis) if a is not None)}
        unaddressed = [axis for axis in range(values.ndim) if axis not in walked]
        if unaddressed:
            names = var.dimensions or ()
            labelled = [
                names[axis] if axis < len(names) else f"axis {axis}"
                for axis in unaddressed
            ]
            subject = "has" if len(labelled) == 1 else "have"
            pronoun = "it" if len(labelled) == 1 else "them"
            raise ValueError(
                f"to_dataframe cannot address variable {var.name!r}: the tidy frame carries one "
                f"row per element with a 'time' and a 'layer' column, and {labelled} "
                f"{subject} no column. Select {pronoun} away first, e.g. with isel()."
            )
        return element_axis, time_axis, layer_axis

    def _arrange_for_rows(
        self, var: MeshVariable, values: np.typing.NDArray
    ) -> tuple[np.typing.NDArray, list[Any], list[Any], bool, bool]:
        """Reorder a variable's axes to ``(time?, layer?, element)`` and label the leading ones.

        The tidy frame walks one row per element, so the axes above the element axis have to be
        walked in a known order with each position labelled. Flattening instead ran the element
        index past the element count and lost which layer a row came from.

        A missing axis is reported as the single label ``[None]``, so the caller's loop runs once
        over it and the frame still carries the column.

        Args:
            var: The variable whose axes are being arranged.
            values: Its values, already gap-masked.

        Returns:
            tuple: ``(arranged, steps, layer_labels, walked_time, walked_layer)`` -- the
            transposed array, one label per time step, one per layer, and whether a time and a
            layer axis were actually walked. The last two matter because they can disagree with
            `var.has_time` / `_layer_axis`: when the dimension names put time (or layer) in the
            element slot, the element reading wins and that axis is *not* walked. A caller that
            trusted `var.has_time` instead indexed `arranged[0]`, slicing the variable down to
            its first element and emitting one row for a two-face mesh.

        Raises:
            ValueError: The variable carries an axis the frame cannot address. The tidy layout is
                one row per element with a ``time`` and a ``layer`` column, so a fourth dimension
                has nowhere to go. Making the transpose a permutation stopped numpy raising, but
                the consumer then folded that axis into the element slot and emitted ``element``
                indices past the element count with NaN coordinates -- a frame a caller joins on,
                which is worse than the exception. Select the extra dimension away first.
        """
        element_axis, time_axis, layer_axis = self._row_axes(var, values)
        leading = [axis for axis in (time_axis, layer_axis) if axis is not None]
        order = [*leading, element_axis]
        arranged = np.transpose(values, order) if values.ndim > 1 else values

        steps: list[Any] = [None]
        if time_axis is not None:
            stamps = var.attributes.get("time_values")
            steps = (
                list(stamps) if stamps is not None else list(range(arranged.shape[0]))
            )

        layer_labels: list[Any] = [None]
        if layer_axis is not None:
            depth = arranged.shape[1 if time_axis is not None else 0]
            stored = var.attributes.get("layer_values")
            layer_labels = list(stored) if stored is not None else list(range(depth))

        return (
            arranged,
            steps,
            layer_labels,
            time_axis is not None,
            layer_axis is not None,
        )

    def _element_coords(self, location: str) -> np.typing.NDArray:
        """The ``(n_elements, 2)`` coordinate table of a mesh facet.

        Args:
            location: ``"face"``, ``"node"`` or ``"edge"``.

        Returns:
            np.ndarray: One ``(x, y)`` row per element, or an empty table when the facet's
            coordinates are not available (an edge-located variable on a mesh carrying no edge
            coordinates), which leaves those rows with a NaN coordinate.
        """
        try:
            table = _location_coords(self._mesh, location)
        except ValueError:
            table = np.empty((0, 2), dtype="float64")
        return np.asarray(table, dtype="float64")

    def _tidy_rows(
        self,
        name: str,
        values: np.typing.NDArray,
        element_coords: np.typing.NDArray,
        step: Any,
        layer: Any = None,
    ) -> pd.DataFrame:
        """One tidy block: every element of ``values`` as a row."""
        flat = np.asarray(values).ravel()
        count = flat.shape[0]
        coords = (
            element_coords
            if element_coords.shape[0] == count
            else np.full((count, 2), np.nan, dtype="float64")
        )
        return pd.DataFrame(
            {
                "variable": np.repeat(name, count),
                "element": np.arange(count),
                "x": coords[:, 0],
                "y": coords[:, 1],
                "layer": np.repeat(layer, count),
                "time": np.repeat(step, count),
                # Keep a non-numeric variable as it is. Forcing float64 raised
                # "could not convert string to float" on exactly the classified /
                # label field `polygonize` recommends.
                "value": (
                    flat.astype("float64")
                    if np.issubdtype(flat.dtype, np.number)
                    else flat
                ),
            }
        )

    def copy(self) -> UgridDataset:
        """An independent deep copy of this dataset.

        Every variable's values are copied, so writing into the copy never shows in the
        original — the counterpart of :meth:`pyramids.netcdf.NetCDF.copy`.

        Returns:
            UgridDataset: The copy.
        """
        copied: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            copied[name] = (
                var
                if var.data is None
                else var.with_data(np.array(var.data, copy=True))
            )
        return type(self)(
            mesh=self._mesh,
            data_variables=copied,
            global_attributes=dict(self._global_attributes),
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )

    @classmethod
    def from_bytes(cls, data: bytes, *, suffix: str = ".nc") -> UgridDataset:
        """Read a UGRID mesh from an in-memory buffer.

        Writes ``data`` into GDAL's in-memory filesystem and reads it as a file, mirroring
        :meth:`pyramids.netcdf.NetCDF.from_bytes` — for a mesh fetched over the network or
        held in a database blob. The values are materialised before the buffer is unlinked, so
        the result does not depend on it.

        Args:
            data: The bytes of a UGRID NetCDF file.
            suffix: The extension to present to GDAL. Defaults to ``".nc"``.

        Returns:
            UgridDataset: The mesh read from the buffer.

        Raises:
            RuntimeError: GDAL cannot read the buffer at all. It is written to ``/vsimem`` and
                read through :meth:`read_file`, so GDAL's own error comes back -- naming the
                in-memory path rather than the caller's bytes.
            ValueError: The buffer reads as a file but declares no UGRID topology.
        """
        name = f"/vsimem/pyramids_ugrid_{uuid4().hex}{suffix}"
        gdal.FileFromMemBuffer(name, data)
        try:
            result = cls.read_file(name).copy()
        finally:
            gdal.Unlink(name)
        return result

    def info(self, buf: Any = None, drivers: bool = False) -> None:
        """Print a summary of the mesh, its variables and its attributes.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.info`: one readable block naming
        the topology, the element counts, the CRS, and every data variable with its location,
        dtype and shape.

        Args:
            buf: Where to write. Defaults to ``sys.stdout``.
            drivers: Also list the mesh file-format drivers available in this interpreter —
                the built-in UGRID reader plus any installed plugin. Off by default because
                resolving them walks every installed distribution, which a summary of one
                dataset should not pay for.
        """
        stream = sys.stdout if buf is None else buf
        lines = [
            f"UgridDataset: {self.mesh_name}",
            f"  nodes: {self.n_node}  faces: {self.n_face}  edges: {self.n_edge}",
            f"  epsg: {self.epsg}",
            f"  variables ({len(self._data_variables)}):",
        ]
        for name, var in self._data_variables.items():
            # Metadata only: `var.data` would fire the lazy loader and pull every variable's
            # full array off disk, which is the opposite of what a summary is for. The declared
            # shape and `has_data_source` answer the same questions without a read.
            shape = str(tuple(var.shape)) if var.has_data_source else "unloaded"
            temporal = "temporal" if var.has_time else "static"
            lines.append(
                f"    {name}: location={var.location} dtype={var.dtype} "
                f"shape={shape} ({temporal})"
            )
        if self._global_attributes:
            lines.append(f"  global attributes ({len(self._global_attributes)}):")
            lines.extend(
                f"    {key}: {value}" for key, value in self._global_attributes.items()
            )
        if drivers:
            driver_lines = describe_drivers()
            # Count the plugins, not the lines: reporting "mesh drivers (1)" on a bare install
            # counted the built-in reader as a driver, while DriverNotExistError described the
            # same state as having none installed.
            plugins = len(driver_lines) - 1
            suffix = "" if plugins == 1 else "s"
            lines.append(f"  mesh drivers (built-in + {plugins} plugin{suffix}):")
            lines.extend(f"    {line}" for line in driver_lines)
        stream.write("\n".join(lines) + "\n")

    def set_global_attribute(self, name: str, value: Any) -> UgridDataset:
        """Return a new dataset carrying one more global attribute.

        A UGRID derivation is immutable here (as :meth:`with_variable` is), so this answers a
        new dataset rather than writing in place; :meth:`to_file` then persists the attributes
        through the shared CF writer.

        Args:
            name: The attribute name.
            value: The attribute value.

        Returns:
            UgridDataset: A new dataset whose global attributes include ``name``.
        """
        return type(self)(
            mesh=self._mesh,
            data_variables=dict(self._data_variables),
            global_attributes={**self._global_attributes, name: value},
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )

    def delete_global_attribute(self, name: str) -> UgridDataset:
        """Return a new dataset without the global attribute ``name``.

        Args:
            name: The attribute to drop. Dropping an absent attribute is not an error,
                mirroring the raster ``delete_global_attribute``.

        Returns:
            UgridDataset: A new dataset without that attribute.
        """
        remaining = {
            key: value for key, value in self._global_attributes.items() if key != name
        }
        return type(self)(
            mesh=self._mesh,
            data_variables=dict(self._data_variables),
            global_attributes=remaining,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )

    def active_mask(self, variable_name: str) -> np.typing.NDArray | None:
        """The variable's per-element active (wet/dry) mask, or ``None`` when it has none.

        The first-class companion of the data (issue #1331): ``True`` marks an active/wet
        element, ``False`` a dry one, kept separate from ``nodata``/NaN so a consumer can tell
        a dry element from a missing value. The mask is element-indexed — ``(n_element,)``
        when it is static or ``(n_time, n_element)`` when it varies per step — and is returned
        as read, never applied to the values. Use :meth:`masked_values` to get the values with
        it applied.

        Args:
            variable_name: Name of the data variable.

        Returns:
            np.ndarray | None: The boolean mask, or ``None`` when the variable carries none.

        Raises:
            KeyError: ``variable_name`` is not a data variable of this dataset.

        Examples:
            - A variable with a mask reports it; one without answers ``None``:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> ds = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"depth": np.array([2.0, 4.0])},
                ... )
                >>> ds["depth"].active = np.array([True, False])
                >>> ds.active_mask("depth").tolist()
                [True, False]
                >>> ds.active_mask("depth") is not None
                True

                ```
        """
        var = self.get_data(variable_name)
        return None if var.active is None else np.asarray(var.active, dtype=bool)

    def masked_values(self, variable_name: str) -> np.typing.NDArray:
        """The variable's values with both ``nodata`` **and** the active mask blanked to NaN.

        The **opt-in** counterpart of a bare ``.data`` read (issue #1331): dry elements (where
        :meth:`active_mask` is ``False``) become NaN on top of the usual ``nodata`` blanking,
        so a caller that wants "treat dry as missing" gets it explicitly — the values are
        never masked by default. Keeps the variable's full shape (every time step and layer),
        unlike the single-step :meth:`sample` / :meth:`weighted` path. When the variable has no
        mask the result is just the ``nodata``-blanked values.

        Args:
            variable_name: Name of the data variable.

        Returns:
            np.ndarray: The float64 values, dry and missing elements alike as NaN.

        Raises:
            KeyError: ``variable_name`` is not a data variable of this dataset.
            ValueError: The variable has no loaded data.

        Examples:
            - Dry elements become NaN, so a mean over the wet cells is straightforward:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> ds = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"depth": np.array([2.0, 4.0])},
                ... )
                >>> ds["depth"].active = np.array([True, False])
                >>> ds.masked_values("depth").tolist()
                [2.0, nan]
                >>> float(np.nanmean(ds.masked_values("depth")))
                2.0

                ```
        """
        var = self.get_data(variable_name)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {variable_name!r} has no loaded data.")
        values = gaps_as_nan(np.asarray(data), var.nodata)
        if var.active is not None:
            values = _apply_active_mask(var, values)
        return cast("np.typing.NDArray", values)

    def _element_values(
        self, variable_name: str, time_index: int = 0, *, apply_active: bool = False
    ) -> tuple[MeshVariable, np.typing.NDArray]:
        """The per-element values of a variable, no-data blanked to NaN.

        Shared by the analysis members (:meth:`sample`, :meth:`weighted`,
        :meth:`zonal_stats`). A temporal variable is reduced to one
        step (``time_index``, the first by default) so the returned array is
        ``(n_elements,)``, matching the single-step contract :meth:`plot` and
        :meth:`to_dataset` already use. The variable's declared no-data value is turned
        into NaN through the shared :func:`pyramids.base._reductions.gaps_as_nan`, so
        every statistic leaves gaps out.

        Args:
            variable_name: Name of the data variable.
            time_index: Which step to take for a temporal variable. Defaults to 0.
            apply_active: Also blank dry elements (:attr:`MeshVariable.active` ``False``) to
                NaN, the mask reduced to the same step. Defaults to ``False`` — the mask is
                never applied unless a caller asks, so "dry" stays distinct from "missing"
                (issue #1331).

        Returns:
            tuple: The :class:`MeshVariable` and its ``(n_elements,)`` float64 values.

        Raises:
            ValueError: The variable has no loaded data, or is not per-element after the
                time collapse (e.g. a layered ``(n_layers, n_face)`` non-temporal variable).
        """
        var = self.get_data(variable_name)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {variable_name!r} has no loaded data.")
        if var.has_time:
            # Take the step along the variable's own time axis, not blindly axis 0 — a
            # mesh variable may store time as a trailing axis (e.g. (nFaces, time)), and
            # the rest of this module keys off var.time_index for exactly that reason.
            data = np.take(
                np.asarray(data), time_index, axis=cast("int", var.time_index)
            )
        result = gaps_as_nan(np.asarray(data), var.nodata)
        if apply_active and var.active is not None and result.ndim == 1:
            # Reduce a per-step mask to the same step, then blank dry elements. A static mask
            # is used as-is. Only meaningful once `result` is the 1-D per-element vector.
            mask = np.asarray(var.active, dtype=bool)
            if mask.ndim >= 2:
                mask = mask[time_index]
            result = np.where(mask, result, np.nan)
        if result.ndim != 1:
            # A non-temporal multi-dimensional variable (e.g. layered (n_layers, n_face))
            # has no single per-element vector; reducing it over an arbitrary axis would
            # silently return a per-column scalar. Refuse rather than mislead.
            raise ValueError(
                f"Variable {variable_name!r} is not per-element after the time collapse "
                f"(shape {result.shape}); the analysis members need a 1-D variable. A "
                "layered/multi-dimensional non-temporal variable is not supported here."
            )
        return var, result

    def summary(
        self,
        variables: Sequence[str] | None = None,
        *,
        metrics: Sequence[str] = DEFAULT_METRICS,
        skipna: bool = True,
        ddof: int = 0,
    ) -> pd.DataFrame:
        """A per-variable summary table over the whole mesh.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.summary`, built on the same shared
        assembly (:func:`pyramids.base._summary.variable_summary`) so the two classes answer in an
        identical shape. Each variable is reduced over **all** of its samples — every element and,
        for a temporal variable, every step — with the declared no-data value left out.

        Args:
            variables: Which data variables to summarise, in output-row order. ``None`` (the
                default) takes every data variable. An unknown name raises ``KeyError``.
            metrics: Which statistics to report, in column order. Defaults to
                ``("count", "min", "max", "mean", "std")``; ``median`` / ``var`` / ``sum`` /
                ``prod`` are available too.
            skipna: Leave no-data out of the statistics (the default) or let it propagate.
            ddof: Delta degrees of freedom for ``std`` / ``var``. Defaults to 0.

        Returns:
            pandas.DataFrame: One row per variable (index name ``"variable"``), one column per
            metric. ``count`` is ``int64``; the rest are ``float64``. A variable with no valid
            element yields NaN statistics and a ``count`` of 0.

        Raises:
            KeyError: A requested variable is not a data variable of this dataset.
            TypeError: A requested variable is non-numeric.
            ValueError: A requested variable has no loaded data, or an unknown metric.

        Examples:
            - Per-variable summary of a two-triangle mesh:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"depth": np.array([2.0, 4.0])},
                ... )
                >>> mesh.summary().loc["depth", ["count", "min", "max", "mean"]].tolist()
                [2.0, 2.0, 4.0, 3.0]

                ```
        """
        names = list(self._data_variables) if variables is None else list(variables)
        arrays: dict[str, np.typing.NDArray] = {}
        for name in names:
            if name not in self._data_variables:
                raise KeyError(name)
            var = self._data_variables[name]
            if var.data is None:
                raise ValueError(f"Variable {name!r} has no loaded data.")
            data = np.asarray(var.data)
            if not np.issubdtype(data.dtype, np.number):
                if variables is None:
                    warnings.warn(
                        f"skipping non-numeric variable {name!r} in summary",
                        stacklevel=2,
                    )
                    continue
                raise TypeError(f"variable {name!r} is non-numeric; cannot summarise")
            arrays[name] = gaps_as_nan(data, var.nodata)
        return variable_summary(arrays, metrics=metrics, skipna=skipna, ddof=ddof)

    def sample(
        self,
        variable_name: str,
        x: float | np.ndarray,
        y: float | np.ndarray,
        *,
        method: str = "contains",
        time_index: int = 0,
    ) -> np.typing.NDArray:
        """Sample a mesh variable at point locations.

        The mesh counterpart of :meth:`pyramids.dataset.Dataset.sample`. Where the raster
        version inverts an affine geotransform to find the pixel under each point, a mesh
        resolves the point to an element through :class:`MeshSpatialIndex`: a face-located
        variable by which face contains the point (``method="contains"``) or the nearest
        face centroid (``method="nearest"``); a node-located variable by nearest node.

        Args:
            variable_name: Name of the data variable.
            x: Query x-coordinate(s), in the mesh CRS.
            y: Query y-coordinate(s), in the mesh CRS.
            method: ``"contains"`` (point-in-face, face variables only) or ``"nearest"``.
                Defaults to ``"contains"``.
            time_index: Step for a temporal variable. Defaults to 0.

        Returns:
            numpy.ndarray: One value per query point; NaN where a ``"contains"`` query
            falls outside every face.

        Raises:
            ValueError: An unknown ``method``, ``"contains"`` on a non-face variable, or a
                variable located on edges (unsupported).
        """
        var, arr = self._element_values(variable_name, time_index=time_index)
        xs = np.atleast_1d(np.asarray(x, dtype="float64"))
        ys = np.atleast_1d(np.asarray(y, dtype="float64"))
        index = MeshSpatialIndex(self._mesh)
        if var.location == "face":
            if method == "contains":
                idx = index.locate_faces(xs, ys)
            elif method == "nearest":
                idx = np.atleast_1d(index.locate_nearest_face(xs, ys)).ravel()
            else:
                raise ValueError(
                    f"sample method must be 'contains' or 'nearest', got {method!r}"
                )
        elif var.location == "node":
            # A node is a point, so "contains" has no meaning here — only "nearest"
            # applies. Reject "contains" rather than silently doing a nearest lookup, as
            # the docstring promises.
            if method == "contains":
                raise ValueError(
                    "sample method='contains' is only valid for a face-located variable; "
                    f"{variable_name!r} is on 'node' — use method='nearest'."
                )
            if method != "nearest":
                raise ValueError(
                    f"sample method must be 'contains' or 'nearest', got {method!r}"
                )
            idx = np.atleast_1d(index.locate_nearest_node(xs, ys)).ravel()
        else:
            raise ValueError(
                f"sample supports 'face' and 'node' variables; {variable_name!r} is on "
                f"{var.location!r}."
            )
        out = np.full(len(xs), np.nan, dtype="float64")
        inside = idx >= 0
        out[inside] = arr[idx[inside]]
        return out

    def weighted(
        self,
        variable_name: str,
        *,
        how: str = "mean",
        time_index: int = 0,
        q: float | None = None,
    ) -> float:
        """Area-weighted statistic of a face variable over the mesh.

        An irregular mesh has faces of different sizes, so the meaningful aggregate weights
        each face by its area. Delegates to the shared
        :func:`pyramids.base._reductions.weighted_statistic` with :attr:`Mesh2d.face_areas`
        as the weights — the same kernel the raster ``weighted`` reduction uses.

        Args:
            variable_name: Name of a **face-located** data variable.
            how: One of ``"mean"``, ``"sum"``, ``"sum_of_weights"``, ``"std"``, ``"var"``,
                ``"quantile"`` (which needs ``q``). Defaults to ``"mean"``.
            time_index: Step for a temporal variable. Defaults to 0.
            q: The quantile in ``[0, 1]`` when ``how="quantile"`` (the area-weighted quantile
                uses the Hazen convention and does not match ``reduce(how="quantile")``); must be
                ``None`` otherwise.

        Returns:
            float: The area-weighted statistic over all faces.

        Raises:
            ValueError: ``how`` is not one of ``WEIGHTED_HOWS``; the variable is not
                face-located; or its length does not match the number of faces.

        Examples:
            - Area-weighted mean: the larger face (area 4, value 10) outweighs the
              smaller (area 2, value 20), pulling the mean below the unweighted 15.0:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 4.0, 4.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 2.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"v": np.array([10.0, 20.0])},
                ... )
                >>> round(mesh.weighted("v"), 3)
                13.333

                ```
            - The area-weighted quantile clamps to the data range at the extremes:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 4.0, 4.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 2.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"v": np.array([10.0, 20.0])},
                ... )
                >>> mesh.weighted("v", how="quantile", q=0.0)
                10.0
                >>> mesh.weighted("v", how="quantile", q=1.0)
                20.0

                ```
        """
        if how not in WEIGHTED_HOWS:
            # Validate up front, mirroring the raster weighted path: the kernel's catch-all
            # else-branch would otherwise return the standard deviation for any unsupported
            # `how`, a silent wrong answer.
            raise ValueError(
                f"weighted: how must be one of {sorted(WEIGHTED_HOWS)}, got {how!r}."
            )
        if how == "quantile":
            if q is None or isinstance(q, bool) or not 0.0 <= float(q) <= 1.0:
                raise ValueError(
                    f"weighted(how='quantile') needs q in [0, 1], got {q!r}."
                )
        elif q is not None:
            raise ValueError(
                f"weighted(q=...) is only valid with how='quantile', not {how!r}."
            )
        var, arr = self._element_values(variable_name, time_index=time_index)
        if var.location != "face":
            raise ValueError(
                "area-weighted statistics need a face-located variable; "
                f"{variable_name!r} is on {var.location!r}."
            )
        areas = self._mesh.face_areas
        if arr.shape[-1] != areas.shape[0]:
            raise ValueError(
                f"variable {variable_name!r} has {arr.shape[-1]} face value(s) but the "
                f"mesh has {areas.shape[0]} face(s)."
            )
        # `arr` already carries NaN for gaps, so `ndv=None` and `skipna=True` reduce over
        # the single face axis; the kernel keeps the axis as length 1, squeezed off here.
        result = weighted_statistic(arr, areas, (0,), how, None, True, q)
        return float(np.asarray(result).ravel()[0])

    def zonal_stats(
        self,
        zones: Any,
        *,
        variable_name: str,
        stats: tuple[str, ...] = ("mean",),
        weighted: bool = True,
        time_index: int = 0,
    ) -> pd.DataFrame:
        """Aggregate a face variable within polygons, weighted by face area.

        The mesh counterpart of :func:`pyramids.dataset.ops._zonal.zonal_stats`. Each face
        is assigned to the zone whose polygon contains its centroid (the mesh analogue of a
        raster pixel's cell centre), then the shared
        :func:`pyramids.base._reductions.reduce_by_label` reduces the face values per zone.
        With ``weighted`` (the default) the **averaging** statistics (``mean`` / ``std`` /
        ``var``) are area-weighted, so a zone's mean is area-exact — a capability the raster
        path does not yet have. ``sum`` is always the plain Σ value (never an area integral),
        and ``count`` / ``min`` / ``max`` are weight-invariant.

        Args:
            zones: Polygons, as a :class:`~pyramids.feature.FeatureCollection` (or any
                object exposing ``geometry``, ``index`` and ``len``). CRS must match the
                mesh; reproject first if not.
            variable_name: Name of a **face-located** data variable.
            stats: Statistics per zone, any of ``"mean"``, ``"sum"``, ``"min"``, ``"max"``,
                ``"std"``, ``"var"``, ``"count"``. Defaults to ``("mean",)``.
            weighted: Area-weight the averaging statistics (``mean`` / ``std`` / ``var``).
                Defaults to True. ``sum`` / ``count`` / ``min`` / ``max`` are unaffected.
            time_index: Step for a temporal variable. Defaults to 0.

        Returns:
            pandas.DataFrame: Indexed like ``zones``; one column per statistic. A zone
            containing no face centroid is NaN (``count`` ``0.0``).

        Raises:
            ValueError: The variable is not face-located, or the zones' CRS disagrees with
                the mesh CRS.
        """
        var, arr = self._element_values(variable_name, time_index=time_index)
        if var.location != "face":
            raise ValueError(
                "mesh zonal_stats needs a face-located variable; "
                f"{variable_name!r} is on {var.location!r}."
            )
        zone_crs = getattr(zones, "crs", None)
        if zone_crs is not None and self.epsg is not None:
            zone_epsg = zone_crs.to_epsg()
            if zone_epsg is not None and zone_epsg != self.epsg:
                raise ValueError(
                    f"zonal_stats: zones CRS (EPSG:{zone_epsg}) does not match mesh CRS "
                    f"(EPSG:{self.epsg}). Reproject the zones to the mesh CRS first."
                )
        geometries = list(zones.geometry)
        cx, cy = self._mesh.face_centroids
        centroids = shapely.points(cx, cy)
        tree = shapely.STRtree(geometries)
        # Face centroid within a zone polygon -> that zone. A centroid in more than one
        # (overlapping zones) keeps the first, mirroring a raster pixel landing in one cell.
        centroid_idx, zone_idx = tree.query(centroids, predicate="within")
        labels = np.full(self._mesh.n_face, -1, dtype=np.intp)
        for face_i, zone_i in zip(centroid_idx, zone_idx):
            if labels[face_i] == -1:
                labels[face_i] = zone_i
        n_zones = len(geometries)
        columns: dict[str, np.typing.NDArray] = {}
        # Area weighting applies only to the averaging statistics. `sum` stays the plain
        # Σ value (a weighted sum would be an area integral — a different quantity, and a
        # silent surprise); `count` / `min` / `max` are weight-invariant anyway.
        averaging = [s for s in stats if s in ("mean", "std", "var")]
        plain = [s for s in stats if s not in ("mean", "std", "var")]
        if weighted and averaging:
            columns.update(
                reduce_by_label(
                    arr, labels, n_zones, averaging, weights=self._mesh.face_areas
                )
            )
            if plain:
                columns.update(reduce_by_label(arr, labels, n_zones, plain))
        else:
            columns.update(reduce_by_label(arr, labels, n_zones, list(stats)))
        return pd.DataFrame({stat: columns[stat] for stat in stats}, index=zones.index)

    def _temporal_names(self) -> list[str]:
        """Names of the variables that carry a real time dimension."""
        return [name for name, var in self._data_variables.items() if var.has_time]

    def _rebuild(self, data_variables: dict[str, MeshVariable]) -> UgridDataset:
        """A new dataset with the same mesh/metadata but different data variables.

        Every along-time member below is immutable — it derives a fresh dataset rather than
        mutating in place — mirroring :meth:`sel_time` / :meth:`crop`. The mesh topology,
        global attributes, topology info, CRS and source file name all carry over unchanged,
        and the result is of the receiver's own class so a subclass is not downgraded.
        """
        return type(self)(
            mesh=self._mesh,
            data_variables=data_variables,
            global_attributes=self._global_attributes,
            topology_info=self._topology_info,
            crs_wkt=self._crs_wkt,
            file_name=self._file_name,
            volume_topology=self._volume_topology,
        )

    def _require_temporal(self, operation: str) -> list[str]:
        """The temporal variable names, or a clear error when there are none."""
        temporal = self._temporal_names()
        if not temporal:
            raise ValueError(
                f"{operation} needs at least one variable with a time dimension; this "
                f"dataset has none."
            )
        return temporal

    def _check_time_dim(self, operation: str, dim: str | None) -> None:
        """Refuse a `dim` that is not the time axis.

        The along-time members take `dim` for signature parity with the raster side, where a
        cube has several non-spatial dimensions to choose from. A mesh has exactly one: the
        element axis is the mesh's own, and carrying a value along it is meaningless. Accept
        ``"time"`` (or ``None``) and refuse anything else rather than silently using time.

        Args:
            operation: The calling method's name, for the message.
            dim: The dimension the caller named, or ``None``.

        Raises:
            ValueError: ``dim`` is neither ``None`` nor ``"time"``.
        """
        if dim is not None and dim != "time":
            raise ValueError(
                f"{operation}: a mesh has one along-able dimension, 'time'; got dim={dim!r}. "
                "The element axis is the mesh's own axis, which carries no ordering to run "
                "along."
            )

    def reduce(
        self,
        how: str,
        *,
        skipna: bool = True,
        q: float | None = None,
        groupby: Any = None,
    ) -> UgridDataset:
        """Reduce the time dimension of every temporal variable, whole or in groups.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.reduce` over time. Each
        temporal variable is reduced along its time axis through the shared
        :func:`pyramids.base._reductions.reduce_axis` — the very kernel the raster reductions
        use. Non-temporal variables are kept unchanged.

        Without ``groupby`` the whole axis collapses to one statistic and the variable becomes
        static. With ``groupby`` each group is reduced on its own slab and the results are
        stacked back along the time axis, so the variable stays temporal with one step per
        group — the same shape contract the raster grouped reduce has. For a ``(4, 2)``
        variable over four monthly steps, ``reduce("mean")`` answers shape ``(2,)`` with
        ``has_time`` False, while ``reduce("mean", groupby="MS")`` answers shape ``(2, 2)``
        with ``has_time`` still True.

        Args:
            how: One of ``"mean"``, ``"sum"``, ``"min"``, ``"max"``, ``"std"``, ``"var"``,
                ``"median"``, ``"prod"``, ``"quantile"``, ``"count"``, ``"all"`` or ``"any"``.
            skipna: Skip the declared no-data value and NaN. Defaults to True.
            q: The quantile for ``how="quantile"``; must stay ``None`` otherwise.
            groupby: Reduce within groups of steps instead of over the whole axis. Two
                spellings, matching the raster grouped reduce: a **sequence of per-step
                labels** the same length as the time axis (grouped in first-appearance order,
                so the caller controls the order), or a **pandas offset alias** (``"MS"``,
                ``"YS"``, …) binned against the dataset's date-like time coordinates. Each
                group's label becomes the result's ``time_values`` entry, and empty bins are
                dropped. ``None`` reduces the whole axis. Defaults to ``None``.

        Returns:
            UgridDataset: A new dataset. Without ``groupby`` each temporal variable is
            collapsed over time into a static per-element variable; with ``groupby`` each one
            keeps its time dimension, at one step per group.

        Raises:
            ValueError: ``how`` is not a known reduction; ``q`` is given for a non-quantile
                ``how`` or missing for ``how="quantile"``; no variable has a time dimension;
                a temporal variable has no loaded data; a ``groupby`` label sequence's length
                is not the time length; or a ``groupby`` offset alias is asked of time
                coordinates that are step positions, or that pandas cannot read as dates.

        Examples:
            - Mean over two time steps of a per-face variable:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"d": np.array([[1.0, 2.0], [3.0, 4.0]])},
                ...     data_locations={"d": "face"},
                ... )
                >>> mesh["d"].has_time
                True
                >>> reduced = mesh.reduce("mean")
                >>> reduced["d"].data.tolist()
                [2.0, 3.0]
                >>> reduced["d"].has_time
                False

                ```
        """
        _check_reduce_how(how, q)
        self._require_temporal("reduce")
        # all/any collapse to a uint8 flag band whose all-gap value is FLAG_NO_DATA (255);
        # the collapsed variable must declare that so a consumer does not read 255 as data.
        result_nodata = FLAG_NO_DATA if how in ("all", "any") else None
        grouped = (
            _group_positions(self._time_coords("reduce"), groupby)
            if groupby is not None
            else None
        )
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to reduce.")
            arr = np.asarray(data)
            nodata = result_nodata if result_nodata is not None else var.nodata
            if grouped is None:
                reduced = reduce_axis(arr, axis, how, skipna, var.nodata, q)
                new_vars[name] = _static_from(
                    var, np.asarray(reduced), axis, nodata=nodata
                )
                continue
            labels, positions = grouped
            # Each group is reduced on its own slab and the results stacked back along the
            # time axis, so a grouped reduce keeps the dimension (shorter) instead of
            # collapsing it — the same shape contract the raster grouped reduce has.
            parts = [
                np.asarray(
                    reduce_axis(
                        np.take(arr, group, axis=axis), axis, how, skipna, var.nodata, q
                    )
                )
                for group in positions
            ]
            # A grouped reduce re-bins the time axis, so a per-step mask no longer aligns —
            # even when n_groups == n_time keeps the shape, which would slip past the
            # length-only implicit guard (review L3). Drop it; a static mask is step-
            # independent and kept.
            new_var = var.with_data(
                np.stack(parts, axis=axis),
                active=None if var.active_has_time else _KEEP_ACTIVE,
            )
            new_var.nodata = nodata
            new_var.attributes = {**var.attributes, "time_values": list(labels)}
            new_vars[name] = new_var
        return self._rebuild(new_vars)

    def resample(
        self,
        freq: str,
        how: str = "mean",
        *,
        skipna: bool = True,
        q: float | None = None,
    ) -> UgridDataset:
        """Bin the time axis by a calendar frequency and reduce each bin.

        Sugar over ``reduce(how, groupby=freq)``: the mesh counterpart of the raster
        ``resample``. The time coordinates must be date-like, since the bins come from a pandas
        offset alias (``"1MS"``, ``"YS"``, ``"7D"``, …). The time dimension is kept, one step
        per non-empty bin, stamped with **pandas' own label for that bin** — which is the bin's
        start for a start-anchored alias and its end for an end-anchored one. Over steps in
        January, February and March 2020, ``"MS"`` labels the bins 01-01 / 02-01 / 03-01 while
        ``"ME"`` labels them 01-31 / 02-29 / 03-31, and ``"W"`` labels each week by its Sunday.

        Args:
            freq: A pandas offset alias naming the bin width.
            how: The statistic each bin is reduced with. Defaults to ``"mean"``.
            skipna: Skip the declared no-data value and NaN. Defaults to True.
            q: The quantile, required when ``how="quantile"``.

        Returns:
            UgridDataset: A new dataset with one time step per bin.

        Raises:
            ValueError: No variable has a time dimension, the coordinates are not date-like,
                or ``how``/``q`` is invalid.
        """
        return self.reduce(how, skipna=skipna, q=q, groupby=freq)

    def mean(self, *, skipna: bool = True) -> UgridDataset:
        """Mean over time of every temporal variable (thin wrapper over :meth:`reduce`).

        Args:
            skipna: Skip the declared no-data value and NaN. Defaults to True.

        Returns:
            UgridDataset: A new dataset; each temporal variable collapsed to its time mean.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self.reduce("mean", skipna=skipna)

    def sum(self, *, skipna: bool = True) -> UgridDataset:
        """Sum over time of every temporal variable (thin wrapper over :meth:`reduce`).

        Args:
            skipna: Skip the declared no-data value and NaN. Defaults to True.

        Returns:
            UgridDataset: A new dataset; each temporal variable collapsed to its time sum.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self.reduce("sum", skipna=skipna)

    def min(self, *, skipna: bool = True) -> UgridDataset:
        """Minimum over time of every temporal variable (thin wrapper over :meth:`reduce`).

        Args:
            skipna: Skip the declared no-data value and NaN. Defaults to True.

        Returns:
            UgridDataset: A new dataset; each temporal variable collapsed to its time minimum.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self.reduce("min", skipna=skipna)

    def max(self, *, skipna: bool = True) -> UgridDataset:
        """Maximum over time of every temporal variable (thin wrapper over :meth:`reduce`).

        Args:
            skipna: Skip the declared no-data value and NaN. Defaults to True.

        Returns:
            UgridDataset: A new dataset; each temporal variable collapsed to its time maximum.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self.reduce("max", skipna=skipna)

    def std(self, *, skipna: bool = True) -> UgridDataset:
        """Std-dev over time of every temporal variable (thin wrapper over :meth:`reduce`).

        Args:
            skipna: Skip the declared no-data value and NaN. Defaults to True.

        Returns:
            UgridDataset: A new dataset; each temporal variable collapsed to its time std.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self.reduce("std", skipna=skipna)

    def var(self, *, skipna: bool = True) -> UgridDataset:
        """Variance over time of every temporal variable (thin wrapper over :meth:`reduce`).

        Args:
            skipna: Skip the declared no-data value and NaN. Defaults to True.

        Returns:
            UgridDataset: A new dataset; each temporal variable collapsed to its time variance.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self.reduce("var", skipna=skipna)

    def _transform_time(
        self, operation: str, fn: Any, active_fn: Any = None
    ) -> UgridDataset:
        """Apply a shape-preserving ``fn(float_data, axis)`` to each temporal variable.

        ``fn`` receives the variable's values as float64 with no-data blanked to NaN, and the
        integer time axis, and returns an array of the same shape. Static variables are kept
        unchanged. Shared by the cumulative, shift, fill and rolling members.

        ``active_fn`` transforms a **per-step** active mask alongside the data. It is needed
        only for an op that *relocates* snapshots along time (``shift``): the implicit mask
        carry keeps a shape-preserving mask as-is, which is right for the value-preserving
        per-step ops (``cumsum``/``cumprod``, ``ffill``/``bfill``, ``rolling`` — step ``t``
        still describes step ``t``) but wrong for ``shift``, where row ``t`` now holds another
        step's snapshot. When given, ``active_fn(mask)`` is applied to a per-step mask (time on
        axis 0) so it moves with the data; a static mask is step-independent and left unchanged.
        """
        self._require_temporal(operation)
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(
                    f"Variable {name!r} has no loaded data for {operation}."
                )
            transformed = fn(gaps_as_nan(np.asarray(data), var.nodata), axis)
            if active_fn is not None and var.active_has_time and var.active is not None:
                moved = var.with_data(
                    np.asarray(transformed),
                    active=active_fn(np.asarray(var.active)),
                )
            else:
                moved = var.with_data(np.asarray(transformed))
            new_vars[name] = moved
        return self._rebuild(new_vars)

    def cumsum(self) -> UgridDataset:
        """Cumulative sum along time for every temporal variable.

        Returns:
            UgridDataset: A new dataset in which each temporal variable holds the running
            sum of its steps along the time axis; static variables are unchanged.

        Raises:
            ValueError: No variable has a time dimension, or a temporal variable has no
                loaded data.

        Examples:
            - Running sum over three time steps of a per-face variable:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"d": np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])},
                ...     data_locations={"d": "face"},
                ... )
                >>> mesh.cumsum()["d"].data.tolist()
                [[1.0, 2.0], [4.0, 6.0], [9.0, 12.0]]

                ```
        """
        return self._transform_time("cumsum", lambda d, axis: np.cumsum(d, axis=axis))

    def cumprod(self) -> UgridDataset:
        """Cumulative product along time for every temporal variable.

        Returns:
            UgridDataset: A new dataset in which each temporal variable holds the running
            product of its steps along the time axis; static variables are unchanged.

        Raises:
            ValueError: No variable has a time dimension, or a temporal variable has no
                loaded data.
        """
        return self._transform_time("cumprod", lambda d, axis: np.cumprod(d, axis=axis))

    def shift(self, periods: int = 1) -> UgridDataset:
        """Shift each temporal variable ``periods`` steps along time, vacated steps NaN.

        Args:
            periods: Steps to shift; negative shifts towards the start. Defaults to 1.

        Returns:
            UgridDataset: A new dataset with each temporal variable shifted along time, the
            vacated steps filled with NaN; static variables are unchanged.

        Raises:
            ValueError: No variable has a time dimension, or a temporal variable has no
                loaded data.
        """
        return self._transform_time(
            "shift",
            lambda d, axis: shifted(d, axis, periods, np.nan),
            # Move a per-step mask with the snapshots (time on axis 0), vacated steps inactive —
            # a shifted-in step holds NaN data, so False is right (review H1).
            active_fn=lambda m: shifted(m, 0, periods, False),
        )

    def _require_variable_name(self, operation: str, variable_name: str | None) -> None:
        """Refuse a ``variable_name`` the dataset does not have.

        The members that sweep every variable skip the names that do not match, so an unknown
        name used to match nothing and return the dataset unchanged — a typo read as a
        successful fit or conversion.

        The wording comes from :func:`unknown_variable_message`, which the facade mixin's
        ``_facade_variable`` also uses, so both halves of the API say the same thing about the
        same mistake. They previously agreed only on the exception *type*: thirteen facade
        members raised a bare ``KeyError('nope')`` naming neither the operation nor the
        available variables.

        Args:
            operation: The calling method's name, for the message.
            variable_name: The requested name, or ``None`` to act on every variable.

        Raises:
            KeyError: ``variable_name`` is not one of the dataset's data variables.
        """
        if variable_name is None or variable_name in self._data_variables:
            return
        raise KeyError(
            unknown_variable_message(
                operation, variable_name, list(self._data_variables)
            )
        )

    def _alongtime_coord(self, operation: str) -> list:
        """The time coordinate the fitting / calculus members work against (issue #1377).

        Uses :attr:`time_values`, which carries real datetimes for a file whose CF time
        coordinate decoded (issue #1381) and positional indices otherwise. The kernels convert
        either to a numeric axis, so an unevenly spaced output interval gives the right rate.

        Args:
            operation: The calling method's name, for the message.

        Returns:
            list: The coordinate values along the time axis.

        Raises:
            ValueError: No variable has a time dimension.
        """
        self._require_temporal(operation)
        coord = self.time_values
        if coord is None:  # pragma: no cover - _require_temporal already guarantees one
            raise ValueError(
                f"{operation} needs a time coordinate; this dataset has none."
            )
        return coord

    def polyfit(self, deg: int, variable_name: str | None = None) -> UgridDataset:
        """Fit a polynomial per element along time, returning its coefficients (#1377).

        The mesh counterpart of the raster ``polyfit``, and what produces a **trend map**: a
        degree-1 fit per face gives the slope of that face's series.

        The time axis is replaced by a ``coefficient`` axis of length ``deg + 1``, highest
        power first — the order :func:`numpy.polyfit` returns. The result is therefore no
        longer a time series, so it is marked static.

        Args:
            deg: Polynomial degree.
            variable_name: Variable to fit (default: every temporal variable).

        Returns:
            UgridDataset: A new dataset whose variables carry the fitted coefficients.

        Raises:
            ValueError: No variable has a time dimension, ``deg`` is negative, or the axis is
                too short for the degree.

        See Also:
            curvefit: Fit an arbitrary model instead of a polynomial.
            differentiate: The instantaneous rate rather than a fitted trend.
        """
        self._require_variable_name("polyfit", variable_name)
        self._alongtime_coord("polyfit")
        return self._fit_alongtime(
            variable_name,
            lambda values, axis, nodata, coord: _timeseries.polyfit_axis(
                values, coord, deg, axis, nodata
            ),
            "coefficient",
        )

    def curvefit(
        self, func: Any, p0: Any = None, variable_name: str | None = None
    ) -> UgridDataset:
        """Fit an arbitrary model per element along time (#1377).

        The general form of :meth:`polyfit`. Each element is fitted in turn, since there is no
        closed form; an element whose fit does not converge yields ``NaN`` parameters rather
        than failing the whole call, so one bad face does not lose the other thousands.

        Args:
            func: The model ``f(x, *params)``. ``x`` is the time coordinate as seconds elapsed
                from the first stamp when the axis carries datetimes.
            p0: Initial parameter guess. Without one the parameter count is read from ``func``'s
                signature.
            variable_name: Variable to fit (default: every temporal variable).

        Returns:
            UgridDataset: A new dataset whose variables carry the fitted parameters along a
            ``parameter`` axis.

        Raises:
            ValueError: No variable has a time dimension.

        See Also:
            polyfit: The closed-form polynomial case, much faster.
        """
        self._require_variable_name("curvefit", variable_name)
        self._alongtime_coord("curvefit")
        return self._fit_alongtime(
            variable_name,
            lambda values, axis, nodata, coord: _timeseries.curvefit_axis(
                values, coord, func, p0, axis, nodata
            ),
            "parameter",
        )

    def _fit_alongtime(
        self,
        variable_name: str | None,
        kernel: Any,
        axis_name: str,
    ) -> UgridDataset:
        """Shared body of :meth:`polyfit` / :meth:`curvefit`.

        Both replace the time axis with a fitted-parameter axis, which makes the result static
        — it is no longer indexed by time — so the time coordinate is dropped with it.

        Args:
            variable_name: Variable to fit, or ``None`` for every temporal one.
            kernel: ``f(values, axis, nodata, coord) -> fitted`` doing the fit. The
                sentinel and the coordinate are both passed per variable, so a declared
                ``-9999`` is excluded and each variable is fitted against its own time axis.
            axis_name: Name for the axis that replaces the time axis — ``"coefficient"`` for
                :meth:`polyfit`, ``"parameter"`` for :meth:`curvefit`.

        Returns:
            UgridDataset: A new dataset carrying the fitted values.

        Raises:
            ValueError: A selected variable has no loaded data to fit.
        """
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time or (
                variable_name is not None and name != variable_name
            ):
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to fit.")
            fitted = kernel(
                np.asarray(data), axis, var.nodata, _variable_time_coord(var)
            )
            dims = _fitted_dimensions(var, fitted.ndim, axis, axis_name)
            attributes = _without_time_metadata(var.attributes)
            new_vars[name] = MeshVariable(
                name=var.name,
                location=var.location,
                mesh_name=var.mesh_name,
                shape=fitted.shape,
                attributes=attributes,
                # Coefficients are a different quantity from the values they were fitted to,
                # so the source's sentinel describes nothing here - and the kernels mark a
                # missing result with NaN, so declaring `-9999` would claim a marker the data
                # does not use. Same reasoning as `_rewrap(keep_nodata=False)`.
                nodata=None,
                units=var.units,
                standard_name=var.standard_name,
                dimensions=dims,
                _data=fitted,
            )
        return self._rebuild(new_vars)

    def differentiate(self, variable_name: str | None = None) -> UgridDataset:
        """The derivative of every temporal variable along time (#1377).

        Honours the time coordinate's own spacing, so an unevenly spaced output interval gives
        the right rate rather than one assuming a uniform step. With a decoded datetime axis
        (issue #1381) the result is **per second**.

        Args:
            variable_name: Variable to differentiate (default: every temporal variable).

        Returns:
            UgridDataset: A new dataset of rates, the same shape as the input.

        Raises:
            ValueError: No variable has a time dimension, or the axis has fewer than two steps.

        See Also:
            integrate: The inverse operation, which consumes the axis.
        """
        self._require_variable_name("differentiate", variable_name)
        self._alongtime_coord("differentiate")
        return self._map_alongtime(
            "differentiate",
            variable_name,
            lambda values, axis, _nodata, coord: _timeseries.differentiate_axis(
                values, coord, axis
            ),
        )

    def cumulative_integrate(self, variable_name: str | None = None) -> UgridDataset:
        """The running integral of every temporal variable along time (#1377).

        Keeps the time axis, unlike :meth:`integrate`. The first step is ``0`` — nothing has
        accumulated yet.

        Args:
            variable_name: Variable to integrate (default: every temporal variable).

        Returns:
            UgridDataset: A new dataset of running integrals, the same shape as the input.

        Raises:
            ValueError: No variable has a time dimension, or the axis has fewer than two steps.

        See Also:
            integrate: The definite integral, which consumes the axis.
        """
        self._require_variable_name("cumulative_integrate", variable_name)
        self._alongtime_coord("cumulative_integrate")
        return self._map_alongtime(
            "cumulative_integrate",
            variable_name,
            lambda values, axis, _nodata, coord: _timeseries.cumulative_integrate_axis(
                values, coord, axis
            ),
        )

    def rank(
        self, variable_name: str | None = None, *, pct: bool = False
    ) -> UgridDataset:
        """Rank each element's values along time, ties averaged (#1377).

        Per face this is an **exceedance map**: where does each step sit among all the steps at
        that face. Needs no date coordinate, so it works on a positional axis too.

        The declared sentinel and ``NaN`` are excluded rather than ranked, as the cube's
        ``rank`` excludes them — ranking a ``-9999`` as the smallest value would shift every
        real rank by one.

        Args:
            variable_name: Variable to rank (default: every temporal variable).
            pct: Report each rank as a fraction of that element's usable values rather than a
                count, so its largest usable value is ``1.0``.

        Returns:
            UgridDataset: A new dataset of ranks, the same shape as the input, counting from 1
            (or in ``(0, 1]`` with ``pct=True``), with ``NaN`` where the value was missing.

        Raises:
            ValueError: No variable has a time dimension.

        See Also:
            idxmax: The step at which each element peaks.
        """
        self._require_variable_name("rank", variable_name)
        self._require_temporal("rank")
        return self._map_alongtime(
            "rank",
            variable_name,
            lambda values, axis, nodata, _coord: _timeseries.rank_axis(
                values, axis, nodata, pct
            ),
        )

    def _map_alongtime(
        self, operation: str, variable_name: str | None, kernel: Any
    ) -> UgridDataset:
        """Apply a shape-preserving along-time kernel to the selected temporal variables.

        The shared body of the members that keep the time axis — :meth:`differentiate`,
        :meth:`cumulative_integrate` and :meth:`rank`.

        Args:
            operation: The calling method's name, for messages.
            variable_name: Variable to transform, or ``None`` for every temporal one.
            kernel: ``f(values, axis, nodata, coord) -> transformed``, which must preserve
                the shape. The sentinel and the coordinate are both passed per variable, so
                each is transformed against its own time axis and its own missing-value
                convention.

        Returns:
            UgridDataset: A new dataset carrying the transformed values.

        Raises:
            ValueError: A selected variable has no loaded data.
        """
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time or (
                variable_name is not None and name != variable_name
            ):
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(
                    f"Variable {name!r} has no loaded data for {operation}."
                )
            transformed = var.with_data(
                kernel(np.asarray(data), axis, var.nodata, _variable_time_coord(var))
            )
            # A rate, a running total or a rank is not the input quantity: the kernels write
            # NaN where the value was missing, so carrying the input's sentinel would declare
            # a marker the result never uses.
            transformed.nodata = None
            new_vars[name] = transformed
        return self._rebuild(new_vars)

    def integrate(self, variable_name: str | None = None) -> UgridDataset:
        """The definite integral of every temporal variable along time (#1377).

        The integral **consumes** the time axis, so the result is static — one value per
        element, as :meth:`reduce` produces. With a decoded datetime axis the units are
        value-seconds.

        Args:
            variable_name: Variable to integrate (default: every temporal variable).

        Returns:
            UgridDataset: A new dataset whose temporal variables are now static totals.

        Raises:
            ValueError: No variable has a time dimension, or the axis has fewer than two steps.

        See Also:
            cumulative_integrate: The running integral, which keeps the axis.
            differentiate: The inverse operation.
        """
        self._require_variable_name("integrate", variable_name)
        self._alongtime_coord("integrate")
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time or (
                variable_name is not None and name != variable_name
            ):
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to integrate.")
            total = _timeseries.integrate_axis(
                np.asarray(data), _variable_time_coord(var), axis
            )
            # The implicit carry is what decides: a static mask survives the collapse (as it
            # does through `reduce`), while a per-step one cannot follow an axis that is gone.
            # Passing `active=None` here force-dropped both.
            collapsed = _static_from(var, total, axis)
            collapsed.attributes = _without_time_metadata(collapsed.attributes)
            # The total is in value-seconds, not the input's units, so the input's sentinel
            # does not describe it.
            collapsed.nodata = None
            new_vars[name] = collapsed
        return self._rebuild(new_vars)

    def coarsen(
        self, window: int, how: str = "mean", variable_name: str | None = None
    ) -> UgridDataset:
        """Block-aggregate the time axis into windows of ``window`` steps (#1377).

        **Not** a duplicate of :meth:`resample`. That one bins by a calendar frequency and so
        needs date-like coordinates; this bins by a **count of steps** and needs no coordinate
        at all, which makes it the only option for a mesh whose file carries no CF time units.
        Where both work, ``resample`` is the calendar-aware choice and this the positional one.

        A trailing remainder shorter than a full window is dropped, so every reported bin is a
        full one rather than a short bin that would read as a dip in the series.

        A variable with fewer steps than one window cannot be binned at all. In a sweep
        (``variable_name=None``) it is passed through untouched, so one short variable does not
        lose the whole call — the choice :meth:`convert_units` makes for a variable with no
        units. Naming such a variable explicitly raises, since that is a request rather than a
        sweep, and so does a sweep in which **no** variable could be binned: that call did
        nothing, and returning the dataset unchanged would look like success.

        Args:
            window: Steps per block, at least 1.
            how: ``"mean"`` (default), ``"sum"``, ``"min"``, ``"max"``, ``"median"`` or
                ``"std"``.
            variable_name: Variable to aggregate (default: every temporal variable).

        Returns:
            UgridDataset: A new dataset whose time axis holds one step per full block, stamped
            with each block's first coordinate value.

        Raises:
            ValueError: No variable has a time dimension, ``window`` is below 1, ``how`` is
                unknown, or the axis is shorter than one window.

        See Also:
            resample: Calendar-frequency binning, when the axis carries real dates.
            reduce: Collapse the whole axis instead of binning it.
        """
        if window < 1:
            raise ValueError(f"coarsen: window must be at least 1, got {window}.")
        self._require_variable_name("coarsen", variable_name)
        self._alongtime_coord("coarsen")
        sweeping = variable_name is None
        new_vars: dict[str, MeshVariable] = {}
        skipped: list[str] = []
        for name, var in self._data_variables.items():
            if not var.has_time or (not sweeping and name != variable_name):
                new_vars[name] = var
                continue
            binned = _coarsened_variable(name, var, window, how, sweeping)
            if binned is None:
                skipped.append(f"{name!r}({var.n_time_steps})")
                new_vars[name] = var
                continue
            new_vars[name] = binned
        if sweeping and len(skipped) == len(
            [v for v in self._data_variables.values() if v.has_time]
        ):
            raise ValueError(
                f"coarsen: no variable has as many as {window} step(s) "
                f"({', '.join(skipped)}), so a window of {window} would report nothing at "
                f"all. Use a smaller window."
            )
        return self._rebuild(new_vars)

    def interp_like(self, other: UgridDataset) -> UgridDataset:
        """Interpolate onto another dataset's time stamps (#1377).

        What lines two runs up on a common axis before :meth:`concat` or an operator. Linear,
        and deliberately **not** extrapolating: a target stamp outside this dataset's span comes
        back as a gap (NaN), which is the contract the raster ``interp`` already has.

        Args:
            other: The dataset whose time coordinate supplies the target stamps. Must sit on
                the same topology.

        Note:
            Two dated axes are put on a common **decimal-year** scale, which means the same
            thing in every calendar, so this works across calendars as well as within one. The
            result declares ``other``'s units and calendar, since those are the stamps it now
            carries; an undated ``other`` leaves the result positional, with no CF metadata at
            all.

        Returns:
            UgridDataset: A new dataset on ``other``'s time stamps, carrying ``other``'s time
            units and calendar (or none, when ``other`` is positional).

        Raises:
            AlignmentError: ``other`` sits on a different mesh.
            ValueError: Either side has no time dimension; this one has fewer than two steps to
                interpolate between; or one side is dated and the other positional, which have
                no common scale.

        See Also:
            interp_time: Interpolate onto a given number of evenly spaced steps.
        """
        self._assert_same_topology(other, "interp_like")
        self._alongtime_coord("interp_like")
        target = other._alongtime_coord("interp_like")
        target_units, target_calendar = other._declared_time_metadata()
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(
                    f"Variable {name!r} has no loaded data to interpolate."
                )
            source_scale, target_scale = _interp_scale(
                _variable_time_coord(var), target
            )
            moved = var.with_data(
                _timeseries.interp_axis(
                    np.asarray(data), source_scale, target_scale, axis
                ),
                # A static mask describes the elements, not the steps, so re-stamping the time
                # axis leaves it valid; only a per-step mask cannot follow. This is the same
                # carry `integrate` and `coarsen` use.
                active=None if var.active_has_time else _KEEP_ACTIVE,
            )
            attributes = {**var.attributes, "time_values": list(target)}
            if target_units is None:
                # The target is positional, so the result's stamps are positions too. Leaving
                # the source's CF units behind would have them re-encoded as real dates that
                # were never in either dataset.
                attributes.pop(TIME_UNITS_ATTR, None)
                attributes.pop(TIME_CALENDAR_ATTR, None)
            else:
                attributes[TIME_UNITS_ATTR] = target_units
                attributes[TIME_CALENDAR_ATTR] = target_calendar
            moved.attributes = attributes
            new_vars[name] = moved
        return self._rebuild(new_vars)

    def _declared_time_metadata(self) -> tuple[str | None, str]:
        """The CF units and calendar this dataset declares, or ``(None, "standard")``.

        Returns:
            tuple: ``(units, calendar)``; ``units`` is ``None`` for a positional axis, which is
            how a caller tells a dated dataset from an undated one.
        """
        for var in self._data_variables.values():
            if var.has_time and TIME_UNITS_ATTR in var.attributes:
                return (
                    str(var.attributes[TIME_UNITS_ATTR]),
                    str(var.attributes.get(TIME_CALENDAR_ATTR) or "standard"),
                )
        return None, "standard"

    def _calendar_instants(self, operation: str) -> tuple[np.ndarray, str, str]:
        """Calendar-aware instants for the time axis, with its CF units and calendar.

        The calendar members need real dates, not positions: "move 29 February onto a
        ``noleap`` axis" is meaningless against a positional index. The stamps come from the CF
        time coordinate the reader decodes (issue #1381), and an axis carrying no CF ``units``
        is refused with a message that says why rather than inventing an epoch.

        Instants are normalised to ``cftime`` objects whatever the reader produced — it yields
        ``datetime64`` for the Gregorian family and ``cftime`` for model calendars, and only
        the latter answers calendar arithmetic.

        Args:
            operation: The calling method's name, for the message.

        Returns:
            tuple: ``(instants, units, calendar)``.

        Raises:
            ValueError: No variable has a time dimension, or the axis carries no CF time units
                and so cannot be re-calendared.
        """
        self._require_temporal(operation)
        stamps = self.time_values
        units = None
        calendar = "standard"
        for var in self._data_variables.values():
            if var.has_time and TIME_UNITS_ATTR in var.attributes:
                units = str(var.attributes[TIME_UNITS_ATTR])
                calendar = str(var.attributes.get(TIME_CALENDAR_ATTR) or "standard")
                break
        if units is None or stamps is None:
            raise ValueError(
                f"{operation}() needs a decoded CF time axis: this dataset's time coordinate "
                f"carries no 'units' attribute of the form '<interval> since <origin>', so its "
                f"steps are positions rather than dates and there is no calendar to convert "
                f"between."
            )
        instants = [_to_cftime(stamp, calendar) for stamp in stamps]
        return np.asarray(instants, dtype=object), units, calendar

    def convert_calendar(
        self, calendar: str, *, align_on: str = "date"
    ) -> UgridDataset:
        """Restamp the time axis onto another CF calendar (issue #1381).

        The mesh counterpart of :meth:`NetCDF.convert_calendar`, and what lets a mesh run on a
        model calendar be compared or :meth:`concat`-enated with one on another.

        **Only the time coordinate changes.** No value is touched and nothing is interpolated:
        each step keeps its values and is given the stamp its date has in the target calendar.
        A date the target has no day for is **dropped, and its step with it** — 29 February
        moving to ``noleap``, 31 December moving to ``360_day`` — so the axis gets shorter.
        :meth:`interp_calendar` is the lossless counterpart.

        Args:
            calendar: The target CF calendar — ``"standard"`` / ``"gregorian"``,
                ``"proleptic_gregorian"``, ``"noleap"`` / ``"365_day"``, ``"all_leap"`` /
                ``"366_day"``, ``"360_day"`` or ``"julian"``.
            align_on: ``"date"`` (default) keeps the calendar date and drops what the target
                lacks. ``"year"`` keeps the *position in the year* instead, which is what a
                ``360_day`` axis of model bookkeeping wants; it loses less, but is not lossless
                either — when the target year is shorter two source days can land on one target
                day, and the duplicates are dropped to keep the axis strictly monotonic.

        Returns:
            UgridDataset: A new dataset whose time axis is restamped onto ``calendar``, carrying
            that calendar and the original units.

        Raises:
            ValueError: The axis carries no CF time units; ``calendar`` is not one ``cftime``
                knows; ``align_on`` is neither ``"date"`` nor ``"year"``; or every step would be
                dropped, which would leave nothing to return.

        See Also:
            interp_calendar: Keeps every step by interpolating instead of dropping.
        """
        if align_on not in _CALENDAR_ALIGNMENTS:
            raise ValueError(
                f"convert_calendar() got align_on={align_on!r}; it must be one of "
                f"{list(_CALENDAR_ALIGNMENTS)}."
            )
        try:
            cftime.datetime(2001, 1, 1, calendar=calendar)
        except (ValueError, KeyError) as error:
            raise ValueError(
                f"convert_calendar() got calendar={calendar!r}, which cftime does not know: "
                f"{error}"
            ) from error
        instants, units, _source = self._calendar_instants("convert_calendar")
        carried, kept = _carried_to_calendar(instants, calendar, align_on)
        if not kept:
            raise ValueError(
                f"convert_calendar() would drop every step: no date on this axis exists in the "
                f"{calendar!r} calendar."
            )
        indices = np.asarray(kept, dtype=np.intp)
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to restamp.")
            active = var.active
            if active is not None and var.active_has_time:
                # The mask is per step, so it loses exactly the steps the values lost.
                active = np.take(np.asarray(active), indices, axis=axis)
            moved = var.with_data(
                np.take(np.asarray(data), indices, axis=axis), active=active
            )
            moved.attributes = {
                **var.attributes,
                "time_values": list(carried),
                TIME_UNITS_ATTR: units,
                TIME_CALENDAR_ATTR: calendar,
            }
            new_vars[name] = moved
        return self._rebuild(new_vars)

    def interp_calendar(self, target: UgridDataset) -> UgridDataset:
        """Interpolate the values onto another dataset's stamps, across calendars (#1381).

        :meth:`convert_calendar`'s lossless counterpart. Where that one restamps the steps it
        has and drops the dates the target calendar lacks, this one **interpolates the values**
        onto the target's own stamps, so no step is lost and the two line up exactly — which is
        what :meth:`concat` or an operator between two runs needs.

        Both axes are put on a common **decimal-year** scale — the year plus the fraction of it
        elapsed — which means the same thing in every calendar: a 360-day and a 365-day year
        both run from ``Y.0`` to ``Y+1.0``.

        Args:
            target: The dataset whose stamps, units and calendar the result takes. Must sit on
                the same topology.

        Returns:
            UgridDataset: A new dataset on ``target``'s stamps, carrying its units and calendar.

        Raises:
            AlignmentError: ``target`` sits on a different mesh.
            ValueError: Either side carries no CF time units; this side has fewer than two steps
                to interpolate between; or the two spans do not overlap at all, so every step
                would come back a gap.

        Note:
            A target stamp inside this dataset's span interpolates; one outside it is a **gap**,
            not an extrapolation. A partly overlapping target therefore comes back partly
            masked, and one that does not overlap at all is refused rather than answered as a
            fully-masked dataset.

        See Also:
            convert_calendar: Restamps without interpolating, dropping absent dates.
        """
        self._assert_same_topology(target, "interp_calendar")
        source_instants, _units, _calendar = self._calendar_instants("interp_calendar")
        target_instants, target_units, target_calendar = target._calendar_instants(
            "interp_calendar"
        )
        source_years = _decimal_years(source_instants)
        target_years = _decimal_years(target_instants)
        if source_years.size < 2:
            raise ValueError(
                f"interp_calendar() needs at least two steps to interpolate between, got "
                f"{source_years.size}."
            )
        if (
            target_years.max() < source_years.min()
            or target_years.min() > source_years.max()
        ):
            raise ValueError(
                "interp_calendar() got a target whose time span does not overlap this "
                "dataset's at all, so every step would come back a gap. Check that the two "
                "runs cover the same period."
            )
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(
                    f"Variable {name!r} has no loaded data to interpolate."
                )
            moved = var.with_data(
                _timeseries.interp_axis(
                    np.asarray(data), source_years, target_years, axis
                ),
                # As in `interp_like`: a static element mask is unaffected by re-stamping.
                active=None if var.active_has_time else _KEEP_ACTIVE,
            )
            moved.attributes = {
                **var.attributes,
                "time_values": list(target_instants),
                TIME_UNITS_ATTR: target_units,
                TIME_CALENDAR_ATTR: target_calendar,
            }
            new_vars[name] = moved
        return self._rebuild(new_vars)

    def to_image(
        self,
        variable_name: str | None = None,
        cell_size: float | None = None,
        cmap: str = "viridis",
        method: str = "nearest",
    ) -> Any:
        """Export a mesh variable as a colour-mapped RGB image (issue #1378).

        An image is a grid of pixels, so the mesh is rasterised first and the raster's own
        :meth:`Dataset.to_image` does the colour mapping — which keeps the colours going
        through cleopatra, as all pyramids rendering does, and keeps one implementation of the
        mapping rather than two that can drift.

        Args:
            variable_name: Variable to render (default: the only one).
            cell_size: Pixel size in coordinate units. ``None`` (default) picks one that puts
                roughly 512 pixels across the mesh's longer side — a readable thumbnail
                without asking the caller to work out a resolution for a mesh whose units
                they may not know.
            cmap: Matplotlib colormap name.
            method: Rasterisation method, ``"nearest"`` (default) or ``"linear"``.

        Returns:
            PIL.Image.Image: The colour-mapped image. The pixels the rasterisation leaves
            empty — those outside the mesh footprint — are no-data, and so are rendered with
            the colormap's "bad" fill colour, exactly as the raster version renders them.
            Requires the ``viz`` extra.

        Raises:
            ValueError: The variable is not one value per element, or no variable is selected
                and the dataset holds more than one.

        See Also:
            to_dataset: The rasterisation this builds on, when you want the grid itself.
            plot: An annotated figure rather than a bare image.
        """
        var = self._facade_variable("to_image", variable_name)
        if var.has_time:
            raise ValueError(
                f"to_image() needs one value per element, but {var.name!r} is a time series "
                f"of {var.n_time_steps} steps. Select a step first, e.g. with isel(time=0)."
            )
        if cell_size is None:
            xmin, ymin, xmax, ymax = self.bounds
            # ~512 px across the longer side: a readable thumbnail without making the caller
            # reason about a resolution in coordinate units they may not know.
            cell_size = max(xmax - xmin, ymax - ymin) / 512.0
        grid = self.to_dataset(var.name, cell_size, method=method)
        return grid.to_image(cmap=cmap)

    def convert_units(
        self, target: str, variable_name: str | None = None
    ) -> UgridDataset:
        """Convert variable values to ``target`` units (issue #1378).

        Mesh variables carry a ``units`` attribute, so the raster's conversion applies
        unchanged — and it is the same affine table
        (:func:`pyramids.dataset.ops.units.convert_array`), so the two sides cannot disagree
        about what a Kelvin is.

        No-data elements keep their sentinel rather than being converted as though they were
        data, which would otherwise turn ``-9999`` into a plausible-looking temperature.

        Args:
            target: Target unit label (e.g. ``"celsius"``, ``"hPa"``, ``"knots"``).
            variable_name: Variable to convert. ``None`` (default) converts every variable
                that declares a unit; one already in ``target`` units passes through unchanged.

        Returns:
            UgridDataset: A new dataset with converted values and the new unit recorded.

        Raises:
            ValueError: A selected variable declares no source unit, or the
                ``(source, target)`` pair is not in the conversion table.

        See Also:
            Dataset.convert_units: The raster counterpart, sharing this table.
        """
        self._require_variable_name("convert_units", variable_name)
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            selected = variable_name is None or name == variable_name
            if not selected or var.units == target:
                new_vars[name] = var
                continue
            if not var.units:
                if variable_name is None:
                    # A sweep over every variable skips the ones with nothing to convert from;
                    # naming one explicitly is a request that must not pass silently.
                    new_vars[name] = var
                    continue
                raise ValueError(
                    f"convert_units() cannot convert {name!r}: it declares no units to "
                    f"convert from. Set its `units` first."
                )
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to convert.")
            values = np.asarray(data, dtype="float64")
            converted = convert_array(values, var.units, target)
            if var.nodata is not None:
                # The sentinel is not a measurement, so it keeps its value.
                converted = np.where(values == var.nodata, values, converted)
            moved = var.with_data(converted)
            moved.units = target
            moved.attributes = {**var.attributes, "units": target}
            new_vars[name] = moved
        return self._rebuild(new_vars)

    def to_dask_dataframe(
        self,
        variables: Sequence[str] | None = None,
        *,
        dropna: bool = False,
        npartitions: int = 1,
    ) -> Any:
        """Hand the mesh to dask in tidy form — the lazy sibling of :meth:`to_dataframe`.

        The mesh's own frame is already tidy (one row per element and step), so this is the
        same shape wrapped in a dask dataframe rather than a different layout.

        **What is and is not deferred:** a mesh's values live in memory, not in a per-element
        chunked store, so there is nothing to stream and the frame is built then partitioned.
        The result is a real dask graph — it composes with the rest of a dask pipeline and
        computes lazily from here on — but it does not reduce the peak memory of building it.
        That is the same thing :meth:`NetCDF.to_dask_dataframe` does for a cube with no
        on-disk store.

        Args:
            variables: Which data variables to include. ``None`` (default) takes them all.
            dropna: Drop rows whose value is no-data. Defaults to False.
            npartitions: How many partitions to split the frame into. Defaults to 1.

        Returns:
            dask.dataframe.DataFrame: The tidy frame as a dask dataframe.

        Raises:
            ImportError: dask (the ``lazy`` extra) or ``dask.dataframe`` (which needs pyarrow,
                the ``parquet`` extra) is not installed.
            ValueError: ``npartitions`` is below 1, or a named variable does not exist.

        See Also:
            to_dataframe: The eager pandas frame this wraps.
        """
        if npartitions < 1:
            raise ValueError(
                f"to_dask_dataframe() got npartitions={npartitions}; it must be at least 1."
            )
        import_dask("to_dask_dataframe() needs dask; install the `lazy` extra.")
        # dask.dataframe (dask-expr) imports pyarrow, which ships in the `parquet` extra rather
        # than `lazy`; guard it so a lazy-only install gets a hint, not a ModuleNotFoundError.
        require_optional(
            "dask.dataframe",
            "to_dask_dataframe() needs dask.dataframe, which requires pyarrow — install the "
            "`parquet` extra (e.g. `pip install pyramids-core[parquet]`).",
        )
        import dask.dataframe as dd

        frame = self.to_dataframe(variables, dropna=dropna)
        return dd.from_pandas(frame, npartitions=npartitions)

    def ffill(
        self, *, limit: int | None = None, dim: str | None = None
    ) -> UgridDataset:
        """Forward-fill gaps along time from the last valid step.

        Args:
            limit: Maximum consecutive gaps one valid step may fill, or ``None`` for no limit.
            dim: The dimension to fill along. A mesh fills along ``"time"`` only, so any other
                name is refused; ``None`` means time. Defaults to ``None``.

        Returns:
            UgridDataset: A new dataset with each temporal variable's gaps carried forward
            from the previous valid step; static variables are unchanged.

        Raises:
            ValueError: ``dim`` names anything but ``"time"``, no variable has a time
                dimension, or a temporal variable has no loaded data.
        """
        self._check_time_dim("ffill", dim)
        return self._transform_time(
            "ffill", lambda d, axis: pushed(d, axis, limit, False)
        )

    def bfill(
        self, *, limit: int | None = None, dim: str | None = None
    ) -> UgridDataset:
        """Back-fill gaps along time from the next valid step.

        Args:
            limit: Maximum consecutive gaps one valid step may fill, or ``None`` for no limit.
            dim: The dimension to fill along. A mesh fills along ``"time"`` only, so any other
                name is refused; ``None`` means time. Defaults to ``None``.

        Returns:
            UgridDataset: A new dataset with each temporal variable's gaps carried backward
            from the next valid step; static variables are unchanged.

        Raises:
            ValueError: ``dim`` names anything but ``"time"``, no variable has a time
                dimension, or a temporal variable has no loaded data.
        """
        self._check_time_dim("bfill", dim)
        return self._transform_time(
            "bfill", lambda d, axis: pushed(d, axis, limit, True)
        )

    def interpolate_na(
        self,
        *,
        method: str = "linear",
        limit: int | None = None,
        use_coordinate: bool = True,
        dim: str | None = None,
    ) -> UgridDataset:
        """Fill each interior time gap by interpolating between the steps on either side.

        Distance is measured along the time coordinate by default, so unevenly spaced steps
        weight their neighbours accordingly; pass ``use_coordinate=False`` to measure by step
        position instead. A leading or trailing gap has only one neighbour and is left alone.

        Args:
            method: One of ``"linear"`` (distance-weighted), ``"nearest"``, or the scipy spline
                kinds ``"slinear"`` / ``"quadratic"`` / ``"cubic"`` (each falling back to linear on
                a variable with too few valid steps). Defaults to ``"linear"``.
            limit: Maximum consecutive gaps a run may fill, or ``None`` for no limit.
            use_coordinate: Measure distance along the time coordinate rather than by step
                position. With time values ``[0, 1, 10]`` and a gap at the middle step, the
                coordinate reading fills ``1.0`` and the positional reading ``5.0``. Date-like
                coordinates count as distances too (converted to nanoseconds), so unevenly
                spaced dates weight their neighbours; a coordinate with no measurable spacing
                (plain labels) falls back to step positions. Defaults to ``True``.
            dim: The dimension to interpolate along. A mesh interpolates along ``"time"``
                only, so any other name is refused; ``None`` means time. Defaults to ``None``.

        Returns:
            UgridDataset: A new dataset with each temporal variable's interior gaps
            interpolated along time; static variables are unchanged.

        Raises:
            ValueError: ``method`` is not one of the accepted interpolations; no variable has a
                time dimension; or a temporal variable has no loaded data.
        """
        if method not in INTERP_METHODS:
            # Validate up front, before the time check, so a bogus method is reported as such
            # even on a mesh with no temporal variable — matching the raster interpolate_na.
            raise ValueError(
                f"interpolate_na() takes method="
                f"{' or '.join(repr(one) for one in INTERP_METHODS)}, got {method!r}."
            )

        self._check_time_dim("interpolate_na", dim)
        stamps = self.time_values if use_coordinate else None
        axis_values = None
        if stamps is not None:
            axis_values = _axis_distances(stamps)

        def _fill(data: np.ndarray, axis: int) -> np.ndarray:
            size = data.shape[axis]
            if axis_values is not None and axis_values.shape[0] == size:
                positions = axis_values
            else:
                positions = np.arange(size, dtype="float64")
            return np.asarray(interpolated(data, axis, positions, method, limit))

        return self._transform_time("interpolate_na", _fill)

    def rolling(
        self,
        window: int,
        how: str = "mean",
        *,
        center: bool = False,
        min_periods: int | None = None,
        q: float | None = None,
        dim: str | None = None,
    ) -> UgridDataset:
        """Rolling-window reduction along time for every temporal variable.

        Each time step becomes a statistic of the window of steps it owns (ending at it, or
        centred on it), cut where the window runs off the axis. Gaps are skipped; a step whose
        window holds fewer than ``min_periods`` valid cells is NaN. The time dimension keeps
        its length.

        Args:
            window: Steps per window.
            how: The reduction over each window (``"mean"``, ``"sum"``, ``"min"``, ``"max"``,
                ``"std"``, ``"var"``, ``"median"``, ``"quantile"``). Defaults to ``"mean"``.
            center: Centre each window on its step rather than ending at it. Defaults to False.
            min_periods: Valid cells a window needs before its step holds a value. ``None``
                means the full ``window``, matching the raster `rolling`, so a step whose
                window runs off the axis is NaN rather than a partial statistic. Defaults to
                ``None``.
            q: The quantile in ``[0, 1]``, required when ``how="quantile"`` and rejected
                otherwise. Defaults to ``None``.
            dim: The dimension to roll along. A mesh rolls along ``"time"`` only, so any
                other name is refused; ``None`` means time. Defaults to ``None``.

        Returns:
            UgridDataset: A new dataset with each temporal variable replaced by its rolling
            statistic along time; static variables are unchanged.

        Raises:
            ValueError: ``how`` is not a known reduction; ``q`` is given for a non-quantile
                ``how`` or missing for ``how="quantile"``; ``window`` is below 1;
                ``min_periods`` falls outside ``[1, window]``; ``dim`` names anything but
                ``"time"``; no variable has a time dimension; or a temporal variable has no
                loaded data.
        """
        if how not in _ROLLING_HOWS:
            # Restrict to the documented statistics. The counting reductions
            # (count/all/any) are excluded on purpose: a window's all/any flag carries the
            # 255 FLAG_NO_DATA sentinel, which would surface as a literal data value here.
            raise ValueError(
                f"rolling how must be one of {sorted(_ROLLING_HOWS)}, got {how!r}."
            )
        # Same guard as every other along-time member, through the shared check rather than
        # a second copy of it with its own wording.
        self._check_time_dim("rolling", dim)
        if how == "quantile" and q is None:
            raise ValueError("rolling(how='quantile') needs q in [0, 1].")
        if how != "quantile" and q is not None:
            raise ValueError(
                f"rolling(q=...) is only valid with how='quantile', not {how!r}."
            )
        if window < 1:
            raise ValueError(f"rolling: window must be >= 1, got {window!r}.")
        # `None` means the full window, as the raster rolling defaults — a step whose window
        # runs off the axis then has no statistic rather than a partial one.
        needed = window if min_periods is None else int(min_periods)
        if not 1 <= needed <= window:
            raise ValueError(
                f"rolling: min_periods must be between 1 and window ({window}), got "
                f"{min_periods!r}."
            )

        def _roll(data: np.ndarray, axis: int) -> np.ndarray:
            moved = np.moveaxis(data, axis, 0)
            size = moved.shape[0]
            out = np.full_like(moved, np.nan, dtype="float64")
            for step in range(size):
                members = window_members(step, size, window, center)
                block = moved[members]
                valid = np.sum(~np.isnan(block), axis=0)
                reduced = reduce_axis(block, 0, how, True, None, q)
                out[step] = np.where(valid >= needed, reduced, np.nan)
            return np.moveaxis(out, 0, axis)

        return self._transform_time("rolling", _roll)

    def _time_length(self, operation: str) -> int:
        """The shared time-axis length across all temporal variables.

        The positional/label selectors build one index set and apply it to every temporal
        variable, so they require a single shared length. Validate that here rather than let
        a mismatch leak a raw numpy ``IndexError`` (or silently trim against the wrong axis).

        Raises:
            ValueError: No variable has a time dimension, or temporal variables disagree on
                their time length.
        """
        temporal = self._require_temporal(operation)
        lengths = {name: self._data_variables[name].n_time_steps for name in temporal}
        distinct = set(lengths.values())
        if len(distinct) > 1:
            raise ValueError(
                f"{operation} needs every temporal variable to share one time length, but "
                f"they differ: {lengths}. Select per variable, or align them first."
            )
        return distinct.pop()

    def _select_steps(self, indices: np.typing.NDArray) -> UgridDataset:
        """Keep the time steps at ``indices`` (in order) for every temporal variable.

        Trims each temporal variable's data along its time axis and, when the variable
        carries a ``time_values`` coordinate attribute, trims that to match. Static variables
        are kept unchanged. The time dimension is retained (shorter), so the result stays
        temporal.
        """
        indices = np.asarray(indices, dtype=np.intp)
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to select.")
            new_var = var.with_data(
                np.take(np.asarray(data), indices, axis=axis),
                active=var._time_indexed_active(indices),
            )
            times = var.attributes.get("time_values")
            if times is not None:
                new_var.attributes = {
                    **var.attributes,
                    "time_values": [times[int(i)] for i in indices],
                }
            new_vars[name] = new_var
        return self._rebuild(new_vars)

    def _select_elements(
        self, element: int | slice | list[int] | np.ndarray
    ) -> UgridDataset:
        """Keep the faces at ``element`` positions, renumbering the mesh around them.

        The element axis is the mesh's own axis, so selecting along it is a *topology* change,
        not a slice: the kept faces' nodes are renumbered compactly and the edges filtered, the
        way :meth:`clip` and :meth:`subset_by_bounds` already do. This shares their machinery
        (:func:`pyramids.netcdf.ugrid.spatial.subset_mesh_by_faces`) rather than re-deriving it.

        Args:
            element: An ``int`` face index, a ``slice``, or a sequence of face indices.

        Returns:
            UgridDataset: A new dataset whose mesh holds only the selected faces.

        Raises:
            IndexError: A face index is out of range for this mesh. A negative index counts
                from the end, so ``-1`` is the last face.
        """
        count = self._mesh.n_face
        if isinstance(element, slice):
            faces = [int(i) for i in np.arange(count)[element]]
        else:
            asked = [int(i) for i in np.atleast_1d(np.asarray(element, dtype=np.intp))]
            # A negative index counts from the end, as `isel(time=-1)` already does through
            # np.take. Refusing it here left one method with two index conventions.
            faces = [i + count if -count <= i < 0 else i for i in asked]
        out_of_range = [i for i in faces if i < 0 or i >= count]
        if out_of_range:
            raise IndexError(
                f"isel: face index/indices {out_of_range} out of range for a mesh with "
                f"{count} face(s)."
            )
        mesh, data_variables = subset_mesh_by_faces(self, faces)
        return self._wrap_subset(mesh, data_variables)

    def isel(
        self,
        time: int | slice | list[int] | np.ndarray | None = None,
        *,
        element: int | slice | list[int] | np.ndarray | None = None,
    ) -> UgridDataset:
        """Select by position along the time axis, the element axis, or both.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.isel`. Over **time** an integer
        selects a single step and collapses the time dimension (the variables become static);
        a slice or sequence keeps the time dimension, trimmed to the chosen steps. Over
        **element** the selection is a topology change: the chosen faces are kept and the mesh
        is renumbered around them (as :meth:`clip` does), so the result is a smaller mesh.
        Giving both applies the element selection first, then the time selection.

        Args:
            time: An ``int`` step, a ``slice``, or a sequence of integer step positions.
                ``None`` (the default) leaves the time axis alone.
            element: An ``int`` face index, a ``slice``, or a sequence of face indices.
                ``None`` (the default) leaves the mesh alone.

        Returns:
            UgridDataset: A new dataset with the selection applied.

        Raises:
            ValueError: Neither ``time`` nor ``element`` was given, or ``time`` was asked of a
                dataset with no time dimension.
            IndexError: A face index is out of range for this mesh.

        Examples:
            - Keep one face, renumbering the mesh around it:
                ```python
                >>> import numpy as np
                >>> from pyramids.netcdf.ugrid import UgridDataset
                >>> mesh = UgridDataset.from_arrays(
                ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
                ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
                ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
                ...     data={"depth": np.array([2.0, 4.0])},
                ... )
                >>> one = mesh.isel(element=0)
                >>> one.n_face, one.n_node
                (1, 3)
                >>> one["depth"].data.tolist()
                [2.0]

                ```
        """
        if time is None and element is None:
            raise ValueError("isel needs `time`, `element`, or both.")
        if element is not None:
            selected = self._select_elements(element)
            return selected if time is None else selected.isel(time)
        n = self._time_length("isel")
        if isinstance(time, (int, np.integer)):
            return self._collapse_to_step(int(time))
        if isinstance(time, slice):
            indices = np.arange(n)[time]
        else:
            indices = np.asarray(time, dtype=np.intp)
        return self._select_steps(indices)

    def _collapse_to_step(self, index: int) -> UgridDataset:
        """Take one time step from every temporal variable, dropping the time dimension.

        The single-step half of :meth:`isel`: each temporal variable becomes static, as
        :meth:`reduce` produces, while a static variable is carried through untouched.

        Args:
            index: The time position to take.

        Returns:
            UgridDataset: A new dataset whose temporal variables hold that step.

        Raises:
            ValueError: A temporal variable has no loaded data.
        """
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to select.")
            step = np.take(np.asarray(data), index, axis=axis)
            new_vars[name] = _static_from(
                var,
                np.asarray(step),
                axis,
                active=var._time_sliced_active(index, None),
            )
        return self._rebuild(new_vars)

    def head(self, n: int = 5) -> UgridDataset:
        """Keep the first ``n`` time steps (fewer if the axis is shorter).

        Args:
            n: Number of leading steps to keep. Defaults to 5.

        Returns:
            UgridDataset: A new dataset trimmed to the first ``n`` steps.

        Raises:
            ValueError: No variable has a time dimension.
        """
        length = self._time_length("head")
        return self._select_steps(np.arange(min(n, length)))

    def tail(self, n: int = 5) -> UgridDataset:
        """Keep the last ``n`` time steps (fewer if the axis is shorter).

        Args:
            n: Number of trailing steps to keep. Defaults to 5.

        Returns:
            UgridDataset: A new dataset trimmed to the last ``n`` steps.

        Raises:
            ValueError: No variable has a time dimension.
        """
        length = self._time_length("tail")
        return self._select_steps(np.arange(max(length - n, 0), length))

    def thin(self, step: int) -> UgridDataset:
        """Keep every ``step``-th time step.

        Args:
            step: Stride; must be >= 1.

        Returns:
            UgridDataset: A new dataset keeping every ``step``-th step.

        Raises:
            ValueError: ``step`` is less than 1, or no variable is temporal.
        """
        if step < 1:
            raise ValueError(f"thin step must be >= 1, got {step}.")
        length = self._time_length("thin")
        return self._select_steps(np.arange(0, length, step))

    def drop_isel(self, indices: int | list[int] | np.ndarray) -> UgridDataset:
        """Drop the time steps at ``indices`` by position, keeping the rest.

        Args:
            indices: A step position, or a sequence of them, to drop (negative indices
                count from the end).

        Returns:
            UgridDataset: A new dataset without the dropped steps.

        Raises:
            ValueError: No variable has a time dimension.
        """
        length = self._time_length("drop_isel")
        drop = {int(i) % length for i in np.atleast_1d(np.asarray(indices))}
        keep = np.array([i for i in range(length) if i not in drop], dtype=np.intp)
        return self._select_steps(keep)

    def squeeze(self) -> UgridDataset:
        """Drop the time dimension when it has length 1; otherwise return unchanged.

        Mirrors :meth:`pyramids.netcdf.NetCDF.squeeze` for the time axis: a single-step
        temporal variable becomes static, a multi-step one is left alone.

        Returns:
            UgridDataset: A new dataset with single-step temporal variables collapsed to
            static, or ``self`` when there is nothing to squeeze.

        Raises:
            ValueError: A single-step temporal variable has no loaded data.
        """
        # Decide per variable, not from the first temporal one: with mixed time lengths a
        # later single-step variable must still be squeezed even if the first has many steps.
        if not any(
            var.has_time and var.n_time_steps == 1
            for var in self._data_variables.values()
        ):
            return self
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time or var.n_time_steps != 1:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to squeeze.")
            # Squeezing the size-1 time axis is taking its single step, so collapse a per-step
            # mask to that step (`mask[0]`) rather than letting the implicit carry drop it as a
            # now-rank-mismatched 2-D mask (review L3). A static mask passes straight through.
            new_vars[name] = _static_from(
                var,
                np.squeeze(np.asarray(data), axis=axis),
                axis,
                active=var._time_sliced_active(0, None),
            )
        return self._rebuild(new_vars)

    def diff(self, n: int = 1) -> UgridDataset:
        """Discrete difference along time (``out[i] = x[i] - x[i-1]``), ``n`` times.

        The time dimension shortens by ``n``; a ``time_values`` coordinate, if present, drops
        its first ``n`` entries to stay aligned with the result.

        Args:
            n: The number of successive differences. Defaults to 1.

        Returns:
            UgridDataset: A new dataset with each temporal variable differenced along time
            (its time axis shorter by ``n``); static variables are unchanged.

        Raises:
            ValueError: No variable has a time dimension, or a temporal variable has no
                loaded data.
        """
        self._require_temporal("diff")
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to diff.")
            diffed = np.diff(gaps_as_nan(np.asarray(data), var.nodata), n=n, axis=axis)
            new_var = var.with_data(diffed)
            times = var.attributes.get("time_values")
            if times is not None:
                new_var.attributes = {**var.attributes, "time_values": list(times[n:])}
            new_vars[name] = new_var
        return self._rebuild(new_vars)

    def _extremum_along_time(
        self, operation: str, *, largest: bool, as_coordinate: bool
    ) -> UgridDataset:
        """Locate each element's extreme time step, as a position or as a coordinate.

        The time axis is dropped — the answer is one value per element — so the result is a
        static variable, as :meth:`reduce` produces. Gaps are left out: the search runs over the
        no-data-masked values, and an element with no valid step at all has no answer, which the
        position form declares as ``-1`` and the coordinate form as NaN (mirroring the raster
        ``argmin`` / ``idxmin``).

        Args:
            operation: The calling method's name, for error messages.
            largest: Search for the maximum rather than the minimum.
            as_coordinate: Answer with the time coordinate value instead of the step position.

        Returns:
            UgridDataset: A new dataset whose temporal variables became static; static
            variables are carried over unchanged.

        Raises:
            ValueError: No variable has a time dimension, a temporal variable has no loaded
                data, or the coordinate form was asked of date-like time coordinates, which
                cannot be expressed as the float64 the answer carries.
        """
        self._require_temporal(operation)
        coords = self._time_coords(operation) if as_coordinate else None
        if coords is not None and not all(
            isinstance(stamp, (int, float, np.integer, np.floating))
            and not isinstance(stamp, bool)
            for stamp in coords
        ):
            # The coordinate form answers float64, so a date-like coordinate cannot be
            # expressed. Say so, rather than letting the float() cast surface a raw
            # TypeError about Timestamp from inside numpy.
            raise ValueError(
                f"{operation}() answers the time coordinate as a float, so it needs numeric "
                "time coordinates; this dataset's are date-like. Use argmin()/argmax() for "
                "the step position instead."
            )
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                new_vars[name] = var
                continue
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data.")
            values, nodata = _extremum_values(
                gaps_as_nan(np.asarray(data), var.nodata),
                axis,
                largest=largest,
                coords=coords if as_coordinate else None,
            )
            new_vars[name] = _static_from(var, values, axis, nodata=nodata)
        return self._rebuild(new_vars)

    def argmin(self) -> UgridDataset:
        """The time-step position of each element's minimum.

        Returns:
            UgridDataset: Static ``int64`` variables holding the step index of the minimum,
            declaring ``-1`` for an element with no valid step.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self._extremum_along_time("argmin", largest=False, as_coordinate=False)

    def argmax(self) -> UgridDataset:
        """The time-step position of each element's maximum.

        Returns:
            UgridDataset: Static ``int64`` variables holding the step index of the maximum,
            declaring ``-1`` for an element with no valid step.

        Raises:
            ValueError: No variable has a time dimension.
        """
        return self._extremum_along_time("argmax", largest=True, as_coordinate=False)

    def idxmin(self) -> UgridDataset:
        """The time **coordinate** of each element's minimum.

        Where :meth:`argmin` answers a step position, this answers the value of the time
        coordinate at that step, so it needs numeric time coordinates.

        Returns:
            UgridDataset: Static ``float64`` variables holding the time coordinate of the
            minimum, NaN where an element has no valid step.

        Raises:
            ValueError: No variable has a time dimension, or the time coordinates are
                date-like rather than numeric (use `argmin` / `argmax` for the step
                position instead).
        """
        return self._extremum_along_time("idxmin", largest=False, as_coordinate=True)

    def idxmax(self) -> UgridDataset:
        """The time **coordinate** of each element's maximum.

        Returns:
            UgridDataset: Static ``float64`` variables holding the time coordinate of the
            maximum, NaN where an element has no valid step.

        Raises:
            ValueError: No variable has a time dimension, or the time coordinates are
                date-like rather than numeric (use `argmin` / `argmax` for the step
                position instead).
        """
        return self._extremum_along_time("idxmax", largest=True, as_coordinate=True)

    def _time_coords(self, operation: str) -> list:
        """The time coordinate values, or a clear error when the dataset has no time."""
        coords = self.time_values
        if coords is None:
            raise ValueError(
                f"{operation} needs a time dimension; this dataset has none."
            )
        return list(coords)

    def sel(
        self,
        time: Any = None,
        *,
        method: str | None = None,
        tolerance: float | None = None,
    ) -> UgridDataset:
        """Select time steps by coordinate value, exactly or by nearest.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.sel` over time. A scalar selects
        one step and collapses the time dimension; a sequence keeps it. Values are matched
        against the dataset's :attr:`time_values` (which fall back to step positions when the
        file carries no explicit time coordinate). ``method="nearest"`` snaps each value to the
        closest coordinate instead of requiring an exact hit, and ``tolerance`` caps how far it
        may snap — the same contract the raster ``sel`` uses, including raising ``KeyError`` (not
        ``ValueError``) when a snap would exceed ``tolerance``.

        Args:
            time: A coordinate value, or a sequence of them.
            method: ``None`` (the default) matches exactly; ``"nearest"`` snaps to the closest
                coordinate, which needs numeric coordinates.
            tolerance: The furthest a ``method="nearest"`` snap may travel. Only valid with
                ``"nearest"``, and must not be negative.

        Returns:
            UgridDataset: A new dataset with the selected steps.

        Raises:
            ValueError: No time dimension; an unknown ``method``; ``tolerance`` without
                ``method="nearest"`` or negative; a value is not among the coordinates (exact
                match); or ``"nearest"`` was asked of non-numeric coordinates.
            KeyError: A ``"nearest"`` snap would exceed ``tolerance``.
        """
        if time is None:
            # `time` is optional in the signature for parity with the raster `sel`, but a
            # missing value has no meaning here. Say so, as `isel` does, instead of
            # reporting that the coordinate [None] was not found.
            raise ValueError(
                "sel needs a time value to select; pass one, or use isel() to select by "
                "position."
            )
        coords = self._time_coords("sel")
        if method not in (None, "nearest"):
            raise ValueError(f"sel: method must be None or 'nearest', got {method!r}.")
        if tolerance is not None:
            if method != "nearest":
                raise ValueError("sel: tolerance is only valid with method='nearest'.")
            if float(tolerance) < 0:
                raise ValueError(
                    f"sel: tolerance must not be negative, got {tolerance!r}."
                )
        wanted = list(time) if isinstance(time, (list, tuple, np.ndarray)) else [time]
        positions = _resolve_time_positions(coords, wanted, method, tolerance)
        if isinstance(time, (list, tuple, np.ndarray)):
            result = self._select_steps(np.asarray(positions, dtype=np.intp))
        else:
            result = self.isel(positions[0])
        return result

    def drop_sel(self, values: Any) -> UgridDataset:
        """Drop the time steps whose coordinate is in ``values``, keeping the rest.

        Args:
            values: A coordinate value, or a sequence of them, to drop.

        Returns:
            UgridDataset: A new dataset without the steps whose coordinate is in ``values``.

        Raises:
            ValueError: No variable has a time dimension.
        """
        coords = self._time_coords("drop_sel")
        drop = (
            set(values)
            if isinstance(values, (list, tuple, set))
            else {*np.atleast_1d(np.asarray(values)).tolist()}
        )
        keep = [i for i, coord in enumerate(coords) if coord not in drop]
        return self._select_steps(np.asarray(keep, dtype=np.intp))

    def sortby(self) -> UgridDataset:
        """Sort the time steps by their coordinate value (stable).

        Returns:
            UgridDataset: A new dataset with steps ordered by ascending time coordinate.

        Raises:
            ValueError: No variable has a time dimension.
        """
        coords = self._time_coords("sortby")
        order = np.argsort(np.asarray(coords), kind="stable")
        return self._select_steps(order)

    def drop_duplicates(self) -> UgridDataset:
        """Keep the first step of each distinct time coordinate value.

        Returns:
            UgridDataset: A new dataset with duplicate-coordinate steps removed, first kept.

        Raises:
            ValueError: No variable has a time dimension.
        """
        coords = self._time_coords("drop_duplicates")
        seen: set = set()
        keep: list[int] = []
        for i, coord in enumerate(coords):
            if coord not in seen:
                seen.add(coord)
                keep.append(i)
        return self._select_steps(np.asarray(keep, dtype=np.intp))

    def dropna(
        self, how: str = "any", thresh: int | None = None, *, dim: str | None = None
    ) -> UgridDataset:
        """Drop time steps that do not hold enough valid cells.

        A step is kept only when **every** temporal variable meets the threshold at that
        step, so the variables stay time-aligned. ``how="any"`` requires every cell of a
        variable to be valid (a single gap drops the step); ``how="all"`` requires at least
        one; ``thresh`` overrides ``how`` with an explicit valid-cell count per variable.

        Args:
            how: ``"any"`` or ``"all"``. Defaults to ``"any"``.
            thresh: Explicit minimum valid-cell count per variable, overriding ``how``.
            dim: The dimension to drop along. A mesh drops along ``"time"`` only, so any other
                name is refused; ``None`` means time. Defaults to ``None``.

        Returns:
            UgridDataset: A new dataset with the surviving steps.

        Raises:
            ValueError: ``how`` is neither ``"any"`` nor ``"all"``; ``dim`` names anything but
                ``"time"``; no variable has a time dimension; a temporal variable has no
                loaded data; or the threshold would drop **every** step, which would leave a
                temporal dataset with no steps for anything downstream to read.
        """
        if how not in ("any", "all"):
            raise ValueError(f"dropna how must be 'any' or 'all', got {how!r}.")
        self._check_time_dim("dropna", dim)
        temporal = self._require_temporal("dropna")
        length = self._time_length("dropna")
        keep = np.ones(length, dtype=bool)
        for name in temporal:
            var = self._data_variables[name]
            axis = cast("int", var.time_index)
            data = var.data
            if data is None:
                raise ValueError(f"Variable {name!r} has no loaded data to dropna.")
            moved = np.moveaxis(gaps_as_nan(np.asarray(data), var.nodata), axis, 0)
            flat = moved.reshape(moved.shape[0], -1)
            per_step_valid = np.sum(~np.isnan(flat), axis=1)
            needed = flat.shape[1] if how == "any" else 1
            if thresh is not None:
                needed = thresh
            keep &= per_step_valid >= needed
        if not keep.any():
            # Returning a zero-length time axis would leave a "temporal" dataset with no
            # steps, which nothing downstream can read; the raster dropna refuses too.
            raise ValueError(
                f"dropna(how={how!r}, thresh={thresh!r}) would drop every one of the "
                f"{length} time step(s); nothing would be left."
            )
        return self._select_steps(np.flatnonzero(keep))

    def _assert_same_topology(self, other: UgridDataset, operation: str) -> None:
        """Refuse ``operation`` unless ``other`` sits on the same mesh as ``self``.

        Same mesh means the same node/face/edge counts and the same node coordinates and
        face-node connectivity — combining data across different meshes is meaningless.
        """
        mine, theirs = self._mesh, other._mesh
        same = (
            mine.n_node == theirs.n_node
            and mine.n_face == theirs.n_face
            and mine.n_edge == theirs.n_edge
            and np.array_equal(mine.node_x, theirs.node_x)
            and np.array_equal(mine.node_y, theirs.node_y)
            and np.array_equal(
                np.asarray(mine.face_node_connectivity.data),
                np.asarray(theirs.face_node_connectivity.data),
            )
        )
        if not same:
            raise AlignmentError(
                f"{operation} requires datasets on the same mesh topology "
                f"(matching node/face/edge counts, coordinates and connectivity)."
            )

    @_joins_meshes
    def concat(self, others: UgridDataset | list[UgridDataset]) -> UgridDataset:
        """Concatenate same-topology datasets along time.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.concat`. Every dataset must sit
        on the same mesh. Each temporal variable's data is concatenated along its time axis
        (and its ``time_values`` coordinate, when present); a static variable is taken from
        ``self`` unchanged. The variable set must match across datasets.

        A **per-step** active mask (:attr:`MeshVariable.active` of shape ``(n_time, n_element)``)
        is **dropped** on concatenation — the parts' masks are not joined along time, and the
        concatenated time length no longer matches ``self``'s mask, so the implicit carry
        discards it (issue #1331). A **static** ``(n_element,)`` mask survives, since it applies
        to every step. Re-attach a per-step mask after concatenating if you need one.

        Args:
            others: One dataset, or a list of them, to append after ``self`` in order.

        Returns:
            UgridDataset: A new dataset spanning the concatenated time axis.

        Raises:
            AlignmentError: A dataset sits on a different mesh. Note this is **not** a
                `ValueError` subclass, so a caller catching `ValueError` around `concat` has
                to catch `AlignmentError` instead.
            ValueError: A dataset carries a different variable set, or a variable has no
                loaded data.
        """
        parts = [
            self,
            *([others] if isinstance(others, UgridDataset) else list(others)),
        ]
        for other in parts[1:]:
            self._assert_same_topology(other, "concat")
            if set(other._data_variables) != set(self._data_variables):
                raise ValueError(
                    "concat requires the same variables in every dataset; got "
                    f"{sorted(self._data_variables)} vs {sorted(other._data_variables)}."
                )
        new_vars: dict[str, MeshVariable] = {}
        for name, var in self._data_variables.items():
            if not var.has_time:
                # Static in self: refuse if any other part has it temporal, rather than
                # silently drop that part's time series (the mirror of the temporal-in-self
                # / static-in-other case _concat_temporal_variable rejects).
                if any(part._data_variables[name].has_time for part in parts[1:]):
                    raise ValueError(
                        f"concat: variable {name!r} is static in one dataset but temporal "
                        "in another; they cannot be joined along time."
                    )
                new_vars[name] = var  # a static variable is taken from self, as-is
            else:
                new_vars[name] = _concat_temporal_variable(name, var, parts)
        return self._rebuild(new_vars)

    @_joins_meshes
    def merge(
        self,
        others: UgridDataset | list[UgridDataset],
        *,
        compat: str = "no_conflicts",
    ) -> UgridDataset:
        """Merge the variables of same-topology datasets into one.

        The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.merge`. Every dataset must sit
        on the same mesh; the union of their variables is returned. A variable name present
        in more than one dataset is a conflict and is refused.

        Args:
            others: One dataset, or a list of them, whose variables join ``self``'s. Under
                the class spelling ``UgridDataset.merge([a, b, c])`` this one argument is the
                whole join: its first element becomes ``self`` and the rest are merged onto it.
            compat: How to handle a variable name present in more than one dataset --
                ``"no_conflicts"`` refuses the collision, ``"override"`` keeps the value from
                the **first dataset in join order that carries the name**: ``self``, then each
                of ``others`` in turn. That is ``self``'s only when ``self`` has the variable;
                when it does not, the first of ``others`` carrying it wins. (Under the class
                spelling ``UgridDataset.merge([a, b, c])``, ``self`` is ``a``.) Defaults to
                ``"no_conflicts"``.

        Returns:
            UgridDataset: A new dataset carrying every variable.

        Raises:
            AlignmentError: A dataset sits on a different mesh.
            ValueError: An unknown ``compat``, or a variable name collides under
                ``compat="no_conflicts"``.
        """
        if compat not in ("no_conflicts", "override"):
            raise ValueError(
                f"merge: compat must be 'no_conflicts' or 'override', got {compat!r}."
            )
        parts = [others] if isinstance(others, UgridDataset) else list(others)
        new_vars: dict[str, MeshVariable] = dict(self._data_variables)
        for other in parts:
            self._assert_same_topology(other, "merge")
            for name, var in other._data_variables.items():
                if name in new_vars:
                    if compat == "no_conflicts":
                        raise ValueError(
                            f"merge: variable {name!r} is present in more than one dataset; "
                            "rename it first, or pass compat='override'."
                        )
                    # compat="override": the first dataset that carries the name wins, which
                    # is what already sits in new_vars, so the duplicate is simply skipped.
                    continue
                new_vars[name] = var
        return self._rebuild(new_vars)

    def plot(
        self,
        variable_name: str,
        ax: Any = None,
        cmap: str = "viridis",
        title: str | None = None,
        basemap: bool | str | None = None,
        colorbar: bool | ColorBar | None = None,
        points: np.ndarray | PointOverlay | None = None,
        kind: str = "auto",
        color: ColorScaling | None = None,
        contour: Contour | None = None,
        data_style: DataStyle | None = None,
        **kwargs: Any,
    ) -> Any:
        """Plot a mesh data variable.

        N-6 — this facade now goes through the same module-level
        helper as the raster path. The mesh-specific dispatch lives in
        :func:`pyramids.dataset._plot_helpers.mesh_render`; both
        ``Dataset.plot``/``NetCDF.plot`` and ``UgridDataset.plot`` share
        the "resolve data, hand to a single helper" contract so the
        two formats no longer maintain independent plotting code paths.

        Args:
            variable_name: Name of the data variable to plot.
            ax: matplotlib Axes. Created if None.
            cmap: Colormap name.
            title: Plot title. Defaults to variable name.
            basemap: If True, add an OpenStreetMap basemap. If a string,
                use it as the tile provider name (e.g. "CartoDB.Positron").
                Default is None (no basemap). Requires the [viz] extra.
            colorbar (bool or ColorBar, optional): Colour-bar spec, part of the
                shared plot signature. A ``pyramids.plot.ColorBar(label=…, …)``
                configures the bar; ``False`` hides it and ``None`` (default) uses
                cleopatra's default (a bar is drawn). Only forwarded when set.
            points (np.ndarray or PointOverlay, optional): Accepted for signature
                symmetry with the raster plot family, but a **no-op here** — a mesh
                has no point-overlay layer (the mesh geometry is the data). Ignored.
            kind (str, optional): Accepted for signature symmetry with the raster
                plot family, but a **no-op here** — ``kind`` selects a raster
                renderer (``imshow``/``pcolormesh``); the mesh always renders via
                ``tripcolor``/``tricontour``. Ignored.
            color (ColorScaling, optional): Colour-scale spec
                ``pyramids.plot.ColorScaling`` (linear / power / sym-log / boundary /
                midpoint norm), e.g. ``ColorScaling.power(gamma=0.7)``. Default ``None``.
            contour (Contour, optional): Contour-line spec
                ``pyramids.plot.Contour(levels=…, label_kw=…)``. Default ``None``.
            data_style (DataStyle, optional): Data-style / relief spec
                ``pyramids.plot.DataStyle(style=…, hillshade=…)``. (A mesh has no
                cell-value overlay, so there is no ``cells`` param here.) Default ``None``.
            **kwargs: Additional arguments passed to mesh_render
                (forwarded to plot_mesh_data). Notably ``colorbar``
                (``bool``, default ``True``): pass ``colorbar=False`` to
                suppress the per-mesh colorbar when you want to attach a
                custom or shared one to ``glyph.ax``. Also ``style`` (name of
                a cleopatra ``DATA_STYLES`` preset, e.g. ``"flow_accumulation"``)
                and ``hillshade`` (``True`` or a params dict) to colour / relief-
                shade the mesh; both require cleopatra >= 0.24 (``hillshade``
                needs node-centered data). Distinct from
                :meth:`pyramids.dataset.Dataset.hillshade`, which *returns* a
                shaded-relief array.

        Returns:
            cleopatra.glyphs.gridded.mesh_glyph.MeshGlyph instance with the plot
                rendered. Use the returned object to access the matplotlib
                handles and the mappable:

                - ``glyph.fig`` / ``glyph.ax`` — Figure and Axes.
                - ``glyph.im`` — the mesh mappable (the
                  ``tripcolor``/``tricontour(f)`` artist) set by ``plot()``;
                  use it for a custom colorbar or ``glyph.im.set_clim(...)``.
                  It is ``None`` after :meth:`plot_outline` (an outline
                  carries no scalar mapping).
                - ``glyph.apply_style(style)`` (cleopatra >= 0.25) — re-apply a
                  ``DATA_STYLES`` preset by name in place, without re-plotting.

        Raises:
            ValueError: If the selected variable has no loaded data, or if
                `basemap` is requested while the dataset has no CRS (`epsg`).
        """
        var = self.get_data(variable_name)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {variable_name!r} has no loaded data to plot.")
        if var.has_time:
            # First step along the variable's own time axis (see `_element_values`).
            data = np.take(np.asarray(data), 0, axis=cast("int", var.time_index))
        if title is None:
            title = variable_name
        if basemap and self.epsg is None:
            raise ValueError("UgridDataset must have a CRS (epsg) to use basemap.")
        # ``points`` / ``kind`` are part of the shared raster-family plot signature
        # but have no meaning for a mesh (no point overlay; the renderer is fixed to
        # tripcolor/tricontour), so they are accepted and ignored. ``colorbar`` and the
        # typed render groups (``color`` / ``contour`` / ``data_style``) map onto the mesh
        # backend and are forwarded only when set (so cleopatra's backend defaults are
        # preserved otherwise).
        if colorbar is not None:
            kwargs["colorbar"] = colorbar
        kwargs.update(
            _nonnull_group_kwargs(color=color, contour=contour, data_style=data_style)
        )
        result = _mesh_render(
            mesh=self._mesh,
            data=data,
            location=var.location,
            ax=ax,
            cmap=cmap,
            title=title,
            basemap=basemap,
            basemap_epsg=self.epsg,
            **kwargs,
        )
        return result

    def animate(
        self,
        variable_name: str | None = None,
        *,
        interval: int = 200,
        **kwargs: Any,
    ) -> Any:
        """Animate a temporal mesh variable over its time axis (issue #1380).

        The mesh had no animation at all, although a mesh time series is one of the most
        natural things to animate — a flood propagating across an unstructured grid. The
        frames come from cleopatra's :meth:`MeshGlyph.animate`, so this is wiring rather than
        new drawing code: the topology stays fixed and each step is drawn on it in turn.

        Args:
            variable_name: Variable to animate (default: the only temporal one).
            interval: Milliseconds between frames. Defaults to 200.
            **kwargs: Forwarded to cleopatra's ``MeshGlyph.animate`` — ``colorbar``, ``color``,
                ``contour``, ``data_style``, ``edgecolor``, ``text_loc``, …

        Returns:
            matplotlib.animation.FuncAnimation: The animation — save it with
            ``anim.save("out.gif")``. Note this differs from :meth:`Dataset.animate` and
            :meth:`NetCDF.animate`, which return a glyph whose ``anim`` attribute holds the
            animation: cleopatra's mesh and array glyph families return different objects and
            pyramids passes each through rather than wrapping one to look like the other.
            **Keep a reference to it** — matplotlib warns and stops an animation that is only
            a temporary, so ``anim = ds.animate()`` plays where a bare ``ds.animate()`` may
            not.

        Raises:
            ValueError: The variable has no time dimension (there would be one frame), or it
                has a dimension besides time and the elements — a layered variable needs a
                layer picked before it can be drawn.

        See Also:
            plot: A single frame.
            Dataset.animate: The raster counterpart, over bands.

        Examples:
            - Animate a water-depth series and save it:
                ```python
                >>> anim = ds.animate("mesh2d_waterdepth", interval=120)  # doctest: +SKIP
                >>> anim.save("depth.gif")  # doctest: +SKIP
                ```
        """
        var = self._facade_variable("animate", variable_name)
        if not var.has_time:
            raise ValueError(
                f"animate() needs a time axis, but {var.name!r} has none — there would be a "
                f"single frame. Use plot() for a static variable."
            )
        data = np.asarray(var.data)
        axis = cast("int", var.time_index)
        frames = np.moveaxis(data, axis, 0)
        if frames.ndim != 2:
            raise ValueError(
                f"animate() draws one value per element per frame, but {var.name!r} has "
                f"shape {data.shape} — a dimension besides time and the elements. Select a "
                f"layer first, e.g. with isel(layer=0) or collapse_layer()."
            )
        # The variable's own coordinate, not the dataset's: `self.time_values` is the FIRST
        # temporal variable's, so animating a second one of a different length failed inside
        # cleopatra ("time length (3) does not match frame count (6)"). Every other along-time
        # member moved onto this helper in 2c8a308; `animate` was missed.
        labels = _variable_time_coord(var)
        return _ugrid_plot.animate_mesh_data(
            self._mesh,
            frames,
            labels,
            location=var.location,
            interval=interval,
            **kwargs,
        )

    def plot_outline(
        self,
        ax: Any = None,
        basemap: bool | str | None = None,
        **kwargs: Any,
    ) -> Any:
        """Plot mesh wireframe.

        Args:
            ax: matplotlib Axes. Created if None.
            basemap: ``True`` or a web-tile provider name, drawing a tile backdrop under the
                wireframe — the same backdrop :meth:`plot` draws under a filled mesh. ``None``
                (default) draws none. The dataset's own ``epsg`` supplies the CRS unless
                ``basemap_epsg`` is passed explicitly, so a mesh with no CRS raises rather
                than mis-placing the tiles (issue #1354).
            **kwargs: Additional arguments passed to plot_mesh_outline.

        Returns:
            cleopatra.glyphs.gridded.mesh_glyph.MeshGlyph instance with the wireframe
                rendered. ``glyph.fig`` / ``glyph.ax`` are the matplotlib
                handles; ``glyph.im`` is ``None`` (an outline carries no
                scalar mapping, so no mappable is produced).
        """
        # `basemap_epsg` is a documented parameter of `plot_mesh_outline`, so passing it
        # here used to collide with the dataset's own CRS ("got multiple values for keyword
        # argument"). An explicit one wins; otherwise the dataset's CRS supplies it.
        kwargs.setdefault("basemap_epsg", self.epsg)
        result = _ugrid_plot.plot_mesh_outline(
            self._mesh,
            ax=ax,
            basemap=basemap,
            **kwargs,
        )
        return result

    def __str__(self) -> str:
        """Human-readable summary of the dataset."""
        lines = [
            f"UgridDataset: {self._file_name or '(in-memory)'}",
            f"  Mesh: {self.mesh_name}",
            f"  Nodes: {self.n_node}, Faces: {self.n_face}, Edges: {self.n_edge}",
            f"  Bounds: {self.bounds}",
            # A mesh may carry a projected WKT with no EPSG code; reporting
            # 'unknown' for a CRS it plainly has was misleading.
            f"  CRS: {self.epsg or (self.crs.name if self.crs is not None else 'unknown')}",
            f"  Data variables ({len(self._data_variables)}):",
        ]
        for name, var in self._data_variables.items():
            lines.append(f"    {name}: location={var.location}, shape={var.shape}")
        result = "\n".join(lines)
        return result

    def __repr__(self) -> str:
        """Repr string for the dataset."""
        result = (
            f"UgridDataset(mesh='{self.mesh_name}', "
            f"n_node={self.n_node}, n_face={self.n_face}, n_edge={self.n_edge}, "
            f"variables={self.data_variable_names})"
        )
        return result

mesh property #

The mesh topology.

mesh_name property #

Name of the mesh topology variable.

data_variable_names property #

Names of all data variables.

crs property #

CRS as a pyproj.CRS object, or None. Cached after first access.

epsg property #

EPSG code of the CRS, or None.

crs_wkt property #

The mesh CRS as WKT, or None when there is none that parses.

Gated on a successful parse rather than returning _crs_wkt verbatim. _crs_wkt is copied straight out of the file and :attr:crs tolerates an unparseable one on purpose, swallowing the error and reporting no CRS. Handing the raw string to a caller would move that parse out from under the handler, so a malformed WKT would start raising downstream instead of being reported as "no CRS" here.

bounds property #

Mesh bounding box as (xmin, ymin, xmax, ymax).

global_attributes property #

File-level NetCDF attributes.

n_node property #

Number of mesh nodes.

n_face property #

Number of mesh faces.

n_edge property #

Number of mesh edges.

data_vars property #

A copy of the {name: variable} mapping.

A fresh dict, so mutating it never changes the dataset — variable edits go through :meth:with_variable / :meth:drop_variables / :meth:rename_variable, which each return a new dataset.

metadata property #

Full metadata summary for this dataset.

time_values property #

Parsed time coordinate values from the first temporal variable.

Returns None if no variables have a time dimension.

volume_topology property #

The ragged (per-column) vertical layering, or None for a uniform / 2-D mesh.

Present only for a genuinely 3-D mesh whose columns carry different layer counts (issue #1330): it maps each face to its slice of the flat volume axis that a location="volume" variable is indexed through. None means the dense (layer, element) path applies — the uniform-layer behaviour is unchanged.

n_volume property #

The total number of volumes, or None when the mesh has no volume topology.

The flat volume-axis length of a ragged 3-D mesh (the sum of every column's layer count). None for a 2-D or uniform-layer mesh, where :attr:n_layers applies instead.

n_layers property #

The number of layers, or None when no variable is layered.

A 3-D mesh output puts some variables on the n layer centres and others on the n + 1 layer interfaces, so two counts differing by one is normal rather than a contradiction; this reports n, the layer count proper. Any other disagreement is a real inconsistency and raises. :meth:isel_layer is unaffected either way — it indexes each variable on its own layer axis.

Reporting n means the n + 1 is not visible here, so a caller iterating range(n_layers) over an interface variable would skip its last interface. Read :attr:n_layer_interfaces for that count rather than inferring it: it answers None unless a variable really sits on the interfaces.

For a ragged 3-D mesh (:attr:volume_topology set) there is no single layer count: this reports the maximum over the columns — the number of layer slots — so range(n_layers) covers the deepest column, and :meth:isel_layer makes the absent shallow-column layers explicit (NaN) rather than padding them silently.

Returns:

Type Description
int | None

int | None: The layer-centre count (the max, for a ragged mesh), or None when

int | None

no variable is layered.

Raises:

Type Description
ValueError

The layered variables carry counts that are not a layer-centre / layer-interface pair.

n_layer_interfaces property #

The number of layer interfaces, or None when nothing sits on them.

The companion to :attr:n_layers. A 3-D output's vertical velocities and fluxes live on the n + 1 interfaces between the n layer centres, and n_layers deliberately reports the centre count -- so this is where the other half of the pair is readable.

It is not simply n_layers + 1, which is always computable: that would assert that something in the dataset is interface-located. Only a variable actually carrying that count makes it true, so a centres-only dataset answers None.

Returns:

Type Description
int | None

int | None: The layer-interface count, or None when no variable is layered or

int | None

every layered variable sits on the centres.

Raises:

Type Description
ValueError

The layered variables carry counts that are not a layer-centre / layer-interface pair -- the same guard :attr:n_layers applies, so the two properties agree about what is readable.

layer_values property #

The layer coordinate values, when a layered variable carries them.

Read from a layered variable's layer_values attribute. The UGRID reader does not populate that attribute -- as with :attr:time_values, the coordinate is supplied by whoever builds or transforms the dataset -- so this is normally None for a mesh read straight from a file, and :meth:sel_layer then selects by layer position.

connected_components() #

Label the mesh's connected face components.

Returns:

Type Description
ndarray

numpy.ndarray: One component label per face.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def connected_components(self) -> np.ndarray:
    """Label the mesh's connected face components.

    Returns:
        numpy.ndarray: One component label per face.
    """
    return _graph.connected_components(self._mesh)  # type: ignore[attr-defined]

focal_mean(rings=1, variable_name=None, reach=None) #

The mean of each face's k-ring neighbourhood, centre included (issue #1376).

The mesh counterpart of the raster focal_mean. The raster version aggregates over a (2*radius+1) pixel window, which has no meaning here — faces have neither a row/column address nor a fixed neighbour count. This aggregates over the faces within rings hops of the face adjacency instead, which is why the parameter is rings and not radius.

Boundary faces aggregate over whatever neighbours they have: no padding, no fabricated values. nodata faces are excluded, and so are inactive ones when the variable carries an active mask — a dry neighbour should not drag a wet face's mean down.

Parameters:

Name Type Description Default
rings int

Adjacency hops the neighbourhood spans. Defaults to 1.

1
variable_name str | None

Variable to act on (default: the only one).

None
reach Any

A neighbourhood matrix to reuse across calls, built with pyramids.netcdf.ugrid.focal.neighbourhood(ds.mesh, rings). Without it each call builds its own, so a sweep over many variables or steps rebuilds the same sparse power every time. Leave rings at its default when passing it.

None

Returns:

Type Description
ndarray

numpy.ndarray: Per-face mean of length n_face; NaN where the neighbourhood

ndarray

holds no usable value.

Raises:

Type Description
ValueError

rings is less than 1, or the variable is not one value per face.

See Also

focal_std: Spread over the same neighbourhood. focal_apply: An arbitrary aggregation over the same neighbourhood.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def focal_mean(
    self,
    rings: int = 1,
    variable_name: str | None = None,
    reach: Any = None,
) -> np.ndarray:
    """The mean of each face's k-ring neighbourhood, centre included (issue #1376).

    The mesh counterpart of the raster ``focal_mean``. The raster version aggregates over a
    ``(2*radius+1)`` **pixel window**, which has no meaning here — faces have neither a
    row/column address nor a fixed neighbour count. This aggregates over the faces within
    ``rings`` hops of the face adjacency instead, which is why the parameter is ``rings``
    and not ``radius``.

    Boundary faces aggregate over whatever neighbours they have: no padding, no fabricated
    values. ``nodata`` faces are excluded, and so are inactive ones when the variable
    carries an active mask — a dry neighbour should not drag a wet face's mean down.

    Args:
        rings: Adjacency hops the neighbourhood spans. Defaults to 1.
        variable_name: Variable to act on (default: the only one).
        reach: A neighbourhood matrix to reuse across calls, built with
            ``pyramids.netcdf.ugrid.focal.neighbourhood(ds.mesh, rings)``. Without it each
            call builds its own, so a sweep over many variables or steps rebuilds the same
            sparse power every time. Leave ``rings`` at its default when passing it.

    Returns:
        numpy.ndarray: Per-face mean of length ``n_face``; ``NaN`` where the neighbourhood
        holds no usable value.

    Raises:
        ValueError: ``rings`` is less than 1, or the variable is not one value per face.

    See Also:
        focal_std: Spread over the same neighbourhood.
        focal_apply: An arbitrary aggregation over the same neighbourhood.
    """
    var, values, active = self._focal_inputs("focal_mean", variable_name)
    return _focal.focal_mean(
        self._mesh,  # type: ignore[attr-defined]
        values,
        rings=rings,
        nodata=var.nodata,
        active=active,
        reach=reach,
    )

focal_std(rings=1, variable_name=None, reach=None) #

The standard deviation of each face's k-ring neighbourhood (issue #1376).

The spread counterpart of :meth:focal_mean, with the same neighbourhood, exclusion and boundary conventions.

Parameters:

Name Type Description Default
rings int

Adjacency hops the neighbourhood spans. Defaults to 1.

1
variable_name str | None

Variable to act on (default: the only one).

None
reach Any

A neighbourhood matrix to reuse across calls, built with pyramids.netcdf.ugrid.focal.neighbourhood(ds.mesh, rings). Without it each call builds its own, so a sweep over many variables or steps rebuilds the same sparse power every time. Leave rings at its default when passing it.

None

Returns:

Type Description
ndarray

numpy.ndarray: Per-face population standard deviation; NaN where the

ndarray

neighbourhood holds no usable value.

Raises:

Type Description
ValueError

rings is less than 1, or the variable is not one value per face.

See Also

focal_mean: The mean over the same neighbourhood.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def focal_std(
    self,
    rings: int = 1,
    variable_name: str | None = None,
    reach: Any = None,
) -> np.ndarray:
    """The standard deviation of each face's k-ring neighbourhood (issue #1376).

    The spread counterpart of :meth:`focal_mean`, with the same neighbourhood, exclusion
    and boundary conventions.

    Args:
        rings: Adjacency hops the neighbourhood spans. Defaults to 1.
        variable_name: Variable to act on (default: the only one).
        reach: A neighbourhood matrix to reuse across calls, built with
            ``pyramids.netcdf.ugrid.focal.neighbourhood(ds.mesh, rings)``. Without it each
            call builds its own, so a sweep over many variables or steps rebuilds the same
            sparse power every time. Leave ``rings`` at its default when passing it.

    Returns:
        numpy.ndarray: Per-face population standard deviation; ``NaN`` where the
        neighbourhood holds no usable value.

    Raises:
        ValueError: ``rings`` is less than 1, or the variable is not one value per face.

    See Also:
        focal_mean: The mean over the same neighbourhood.
    """
    var, values, active = self._focal_inputs("focal_std", variable_name)
    return _focal.focal_std(
        self._mesh,  # type: ignore[attr-defined]
        values,
        rings=rings,
        nodata=var.nodata,
        active=active,
        reach=reach,
    )

focal_apply(func, rings=1, variable_name=None, reach=None) #

Aggregate each face's k-ring neighbourhood with func (issue #1376).

func receives the 1-D array of usable values in one neighbourhood and returns a scalar, so np.ptp, np.median or a lambda all work. Unlike :meth:focal_mean and :meth:focal_std this cannot be expressed as a sparse product, so it visits each face in turn — noticeably slower on a large mesh, which is the price of an arbitrary aggregation.

Parameters:

Name Type Description Default
func Any

Callable taking a 1-D array and returning a scalar.

required
rings int

Adjacency hops the neighbourhood spans. Defaults to 1.

1
variable_name str | None

Variable to act on (default: the only one).

None
reach Any

A neighbourhood matrix to reuse across calls, built with pyramids.netcdf.ugrid.focal.neighbourhood(ds.mesh, rings). Without it each call builds its own, so a sweep over many variables or steps rebuilds the same sparse power every time. Leave rings at its default when passing it.

None

Returns:

Type Description
ndarray

numpy.ndarray: Per-face aggregate; NaN where the neighbourhood holds no usable

ndarray

value, so func is never handed an empty array.

Raises:

Type Description
ValueError

rings is less than 1, or the variable is not one value per face.

See Also

focal_mean: The vectorised mean, when that is all you need.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def focal_apply(
    self,
    func: Any,
    rings: int = 1,
    variable_name: str | None = None,
    reach: Any = None,
) -> np.ndarray:
    """Aggregate each face's k-ring neighbourhood with ``func`` (issue #1376).

    ``func`` receives the 1-D array of usable values in one neighbourhood and returns a
    scalar, so ``np.ptp``, ``np.median`` or a lambda all work. Unlike :meth:`focal_mean`
    and :meth:`focal_std` this cannot be expressed as a sparse product, so it visits each
    face in turn — noticeably slower on a large mesh, which is the price of an arbitrary
    aggregation.

    Args:
        func: Callable taking a 1-D array and returning a scalar.
        rings: Adjacency hops the neighbourhood spans. Defaults to 1.
        variable_name: Variable to act on (default: the only one).
        reach: A neighbourhood matrix to reuse across calls, built with
            ``pyramids.netcdf.ugrid.focal.neighbourhood(ds.mesh, rings)``. Without it each
            call builds its own, so a sweep over many variables or steps rebuilds the same
            sparse power every time. Leave ``rings`` at its default when passing it.

    Returns:
        numpy.ndarray: Per-face aggregate; ``NaN`` where the neighbourhood holds no usable
        value, so ``func`` is never handed an empty array.

    Raises:
        ValueError: ``rings`` is less than 1, or the variable is not one value per face.

    See Also:
        focal_mean: The vectorised mean, when that is all you need.
    """
    var, values, active = self._focal_inputs("focal_apply", variable_name)
    return _focal.focal_apply(
        self._mesh,  # type: ignore[attr-defined]
        values,
        func,
        rings=rings,
        nodata=var.nodata,
        active=active,
        reach=reach,
    )

slope(units='degrees', variable_name=None) #

Per-face slope of a mesh DEM, in degrees (default) or radians (issue #1374).

An unstructured bed-level mesh is a DEM. The raster version reads a 3x3 pixel window, which has no mesh equivalent; this fits a plane through each face's own node elevations and reads the slope off that -- exact for a triangle, least-squares for a polygon.

Parameters:

Name Type Description Default
units str

"degrees" (default) or "radians".

'degrees'
variable_name str | None

The elevation variable (default: the only one). A face-located one is averaged onto the nodes first.

None

Returns:

Type Description
ndarray

numpy.ndarray: Per-face slope of length n_face; NaN on a degenerate face,

ndarray

and on any face touching a nodata elevation — a void has no defined gradient,

ndarray

which is the contract the raster kernels state too.

Raises:

Type Description
ValueError

units is invalid, the variable is edge-located, or it is not one value per element.

See Also

aspect: The direction the slope faces. hillshade: Shaded relief from the same gradient.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def slope(
    self, units: str = "degrees", variable_name: str | None = None
) -> np.ndarray:
    """Per-face slope of a mesh DEM, in degrees (default) or radians (issue #1374).

    An unstructured bed-level mesh is a DEM. The raster version reads a 3x3 pixel window,
    which has no mesh equivalent; this fits a plane through each face's own node elevations
    and reads the slope off that -- exact for a triangle, least-squares for a polygon.

    Args:
        units: ``"degrees"`` (default) or ``"radians"``.
        variable_name: The elevation variable (default: the only one). A face-located one
            is averaged onto the nodes first.

    Returns:
        numpy.ndarray: Per-face slope of length ``n_face``; ``NaN`` on a degenerate face,
        and on any face touching a ``nodata`` elevation — a void has no defined gradient,
        which is the contract the raster kernels state too.

    Raises:
        ValueError: ``units`` is invalid, the variable is edge-located, or it is not one
            value per element.

    See Also:
        aspect: The direction the slope faces.
        hillshade: Shaded relief from the same gradient.
    """
    return _terrain.slope(
        self._mesh,  # type: ignore[attr-defined]
        self._elevation_nodes("slope", variable_name),
        units=units,
    )

aspect(variable_name=None) #

Per-face aspect of a mesh DEM, in degrees clockwise from north (issue #1374).

Names the direction the slope faces (downhill), matching the raster convention: a surface rising to the east faces west, 270 degrees.

Parameters:

Name Type Description Default
variable_name str | None

The elevation variable (default: the only one).

None

Returns:

Type Description
ndarray

numpy.ndarray: Per-face aspect in [0, 360); NaN on a degenerate face, and

ndarray

on any face touching a nodata elevation.

Raises:

Type Description
ValueError

The variable is edge-located, or is not one value per element.

See Also

slope: The magnitude of the same gradient.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def aspect(self, variable_name: str | None = None) -> np.ndarray:
    """Per-face aspect of a mesh DEM, in degrees clockwise from north (issue #1374).

    Names the direction the slope **faces** (downhill), matching the raster convention: a
    surface rising to the east faces west, 270 degrees.

    Args:
        variable_name: The elevation variable (default: the only one).

    Returns:
        numpy.ndarray: Per-face aspect in ``[0, 360)``; ``NaN`` on a degenerate face, and
        on any face touching a ``nodata`` elevation.

    Raises:
        ValueError: The variable is edge-located, or is not one value per element.

    See Also:
        slope: The magnitude of the same gradient.
    """
    return _terrain.aspect(
        self._mesh,  # type: ignore[attr-defined]
        self._elevation_nodes("aspect", variable_name),
    )

hillshade(azimuth=315.0, altitude=45.0, variable_name=None) #

Per-face shaded relief of a mesh DEM, clipped to 0..255 (issue #1374).

Parameters:

Name Type Description Default
azimuth float

Sun azimuth in degrees (0 = north, 90 = east). Defaults to 315 (NW).

315.0
altitude float

Sun altitude above the horizon in degrees. Defaults to 45.

45.0
variable_name str | None

The elevation variable (default: the only one).

None

Returns:

Type Description
ndarray

numpy.ndarray: Per-face intensity in [0, 255]; NaN on a degenerate face,

ndarray

and on any face touching a nodata elevation. A

ndarray

flat mesh saturates at sin(altitude) * 255, as the raster version does.

Raises:

Type Description
ValueError

The variable is edge-located, or is not one value per element.

See Also

slope: The slope magnitude the shading is derived from.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def hillshade(
    self,
    azimuth: float = 315.0,
    altitude: float = 45.0,
    variable_name: str | None = None,
) -> np.ndarray:
    """Per-face shaded relief of a mesh DEM, clipped to ``0..255`` (issue #1374).

    Args:
        azimuth: Sun azimuth in degrees (0 = north, 90 = east). Defaults to 315 (NW).
        altitude: Sun altitude above the horizon in degrees. Defaults to 45.
        variable_name: The elevation variable (default: the only one).

    Returns:
        numpy.ndarray: Per-face intensity in ``[0, 255]``; ``NaN`` on a degenerate face,
        and on any face touching a ``nodata`` elevation. A
        flat mesh saturates at ``sin(altitude) * 255``, as the raster version does.

    Raises:
        ValueError: The variable is edge-located, or is not one value per element.

    See Also:
        slope: The slope magnitude the shading is derived from.
    """
    return _terrain.hillshade(
        self._mesh,  # type: ignore[attr-defined]
        self._elevation_nodes("hillshade", variable_name),
        azimuth=azimuth,
        altitude=altitude,
    )

cluster(lower, upper, variable_name=None) #

Label connected groups of faces whose values fall in [lower, upper] (#1379).

The value-aware sibling of :meth:connected_components, and the mesh counterpart of the raster cluster. :meth:connected_components labels by topology alone, so it cannot answer "which separate pools of flooded cells are there"; this restricts the face adjacency to the faces inside the range before labelling.

Faces outside the range — and no-data faces, which cannot be inside one — are labelled 0, so a label is truthy exactly when the face belongs to a cluster. Clusters are numbered 1..k.

Parameters:

Name Type Description Default
lower float

Inclusive lower bound.

required
upper float

Inclusive upper bound.

required
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset whose variable carries the per-face cluster labels.

Raises:

Type Description
ValueError

The variable is not one value per face (select a step first).

See Also

connected_components: Topology-only labelling, ignoring values. footprint: The dissolved outline of the faces carrying valid values.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def cluster(
    self,
    lower: float,
    upper: float,
    variable_name: str | None = None,
) -> Any:
    """Label connected groups of faces whose values fall in ``[lower, upper]`` (#1379).

    The value-aware sibling of :meth:`connected_components`, and the mesh counterpart of
    the raster ``cluster``. :meth:`connected_components` labels by **topology alone**, so
    it cannot answer "which separate pools of flooded cells are there"; this restricts the
    face adjacency to the faces inside the range before labelling.

    Faces outside the range — and no-data faces, which cannot be inside one — are labelled
    ``0``, so a label is truthy exactly when the face belongs to a cluster. Clusters are
    numbered ``1..k``.

    Args:
        lower: Inclusive lower bound.
        upper: Inclusive upper bound.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset whose variable carries the per-face cluster labels.

    Raises:
        ValueError: The variable is not one value per face (select a step first).

    See Also:
        connected_components: Topology-only labelling, ignoring values.
        footprint: The dissolved outline of the faces carrying valid values.
    """
    var = self._facade_variable("cluster", variable_name)
    labels = _graph.value_clusters(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        lower,
        upper,
        var.nodata,
    )
    return self._rewrap(var, labels, keep_nodata=False)

footprint(variable_name=None) #

The dissolved outline of the faces carrying valid values (#1379).

The mesh counterpart of the raster footprint — "the real coverage of the values". Distinct from :meth:bounding_polygon, which dissolves every face and so describes the mesh domain rather than where data exists, and from :meth:polygonize, which returns one polygon per distinct value.

"Valid" means not nodata and not NaN. It deliberately does not consult the per-timestep active mask: a dry element has a real value and is still covered by the data, so excluding it would conflate "no data here" with "dry here", which is the distinction issue #1331 exists to preserve. For the wet extent, mask first (:meth:masked_values or :meth:where) and take the footprint of that.

Parameters:

Name Type Description Default
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Type Description
Any

shapely.Polygon | shapely.MultiPolygon: The dissolved coverage, empty when no face

Any

carries a valid value. Carries no CRS — attach one if you need it.

Raises:

Type Description
ValueError

The variable is not one value per face (select a step first).

See Also

bounding_polygon: The whole mesh outline, data or not. polygonize: One polygon per distinct value.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def footprint(self, variable_name: str | None = None) -> Any:
    """The dissolved outline of the faces carrying valid values (#1379).

    The mesh counterpart of the raster ``footprint`` — "the real coverage of the values".
    Distinct from :meth:`bounding_polygon`, which dissolves **every** face and so describes
    the mesh *domain* rather than where data exists, and from :meth:`polygonize`, which
    returns one polygon per distinct value.

    "Valid" means not ``nodata`` and not NaN. It deliberately does **not** consult the
    per-timestep active mask: a dry element has a real value and is still covered by the
    data, so excluding it would conflate "no data here" with "dry here", which is the
    distinction issue #1331 exists to preserve. For the wet extent, mask first
    (:meth:`masked_values` or :meth:`where`) and take the footprint of that.

    Args:
        variable_name: Variable to act on (default: the only one).

    Returns:
        shapely.Polygon | shapely.MultiPolygon: The dissolved coverage, empty when no face
        carries a valid value. Carries no CRS — attach one if you need it.

    Raises:
        ValueError: The variable is not one value per face (select a step first).

    See Also:
        bounding_polygon: The whole mesh outline, data or not.
        polygonize: One polygon per distinct value.
    """
    var = self._facade_variable("footprint", variable_name)
    return _graph.valid_footprint(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        var.nodata,
    )

exterior_edges() #

The indices of the edges on the mesh boundary.

Returns:

Type Description
ndarray

numpy.ndarray: Boundary edge indices.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def exterior_edges(self) -> np.ndarray:
    """The indices of the edges on the mesh boundary.

    Returns:
        numpy.ndarray: Boundary edge indices.
    """
    return _graph.exterior_edges(self._mesh)  # type: ignore[attr-defined]

exterior_faces() #

The indices of the faces touching the mesh boundary.

Returns:

Type Description
ndarray

numpy.ndarray: Boundary face indices.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def exterior_faces(self) -> np.ndarray:
    """The indices of the faces touching the mesh boundary.

    Returns:
        numpy.ndarray: Boundary face indices.
    """
    return _graph.exterior_faces(self._mesh)  # type: ignore[attr-defined]

bounding_polygon() #

The mesh footprint as one dissolved polygon, holes preserved.

Returns:

Type Description
Any

shapely.geometry.base.BaseGeometry: The (multi)polygon of the mesh outline.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def bounding_polygon(self) -> Any:
    """The mesh footprint as one dissolved polygon, holes preserved.

    Returns:
        shapely.geometry.base.BaseGeometry: The (multi)polygon of the mesh outline.
    """
    return _graph.bounding_polygon(self._mesh)  # type: ignore[attr-defined]

circumcenters() #

The circumcentre of every face (triangular meshes only).

Returns:

Type Description
ndarray

numpy.ndarray: (n_face, 2) circumcentre coordinates.

Raises:

Type Description
ValueError

The mesh is not triangular.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def circumcenters(self) -> np.ndarray:
    """The circumcentre of every face (triangular meshes only).

    Returns:
        numpy.ndarray: ``(n_face, 2)`` circumcentre coordinates.

    Raises:
        ValueError: The mesh is not triangular.
    """
    return _graph.circumcenters(self._mesh)  # type: ignore[attr-defined]

voronoi() #

The Voronoi tesselation of the mesh nodes (the mesh dual).

Returns:

Type Description
Any

scipy.spatial.Voronoi: The tesselation.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def voronoi(self) -> Any:
    """The Voronoi tesselation of the mesh nodes (the mesh dual).

    Returns:
        scipy.spatial.Voronoi: The tesselation.
    """
    return _graph.voronoi(self._mesh)  # type: ignore[attr-defined]

sparse_adjacency(kind='face') #

The mesh adjacency as a sparse matrix.

Parameters:

Name Type Description Default
kind str

"face" (faces sharing an edge) or "node" (nodes sharing an edge).

'face'

Returns:

Type Description
Any

scipy.sparse.csr_matrix: The symmetric adjacency.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def sparse_adjacency(self, kind: str = "face") -> Any:
    """The mesh adjacency as a sparse matrix.

    Args:
        kind: ``"face"`` (faces sharing an edge) or ``"node"`` (nodes sharing an edge).

    Returns:
        scipy.sparse.csr_matrix: The symmetric adjacency.
    """
    return _graph.sparse_adjacency(self._mesh, kind)  # type: ignore[attr-defined]

binary_dilation(variable_name=None, *, iterations=1, border_value=False, fixed=None) #

Grow a boolean face mask over its neighbours.

Parameters:

Name Type Description Default
variable_name str | None

The boolean face variable to dilate, or None for the only one.

None
iterations int

How many times to grow. Defaults to 1.

1
border_value bool

What lies outside the mesh. Defaults to False.

False
fixed ndarray | None

A boolean per-face mask of the cells the result must preserve, whatever the dilation would do to them — scipy's mask argument. None leaves every face free to change. Defaults to None.

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with the dilated mask.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def binary_dilation(
    self,
    variable_name: str | None = None,
    *,
    iterations: int = 1,
    border_value: bool = False,
    fixed: np.ndarray | None = None,
) -> Any:
    """Grow a boolean face mask over its neighbours.

    Args:
        variable_name: The boolean face variable to dilate, or ``None`` for the only one.
        iterations: How many times to grow. Defaults to 1.
        border_value: What lies outside the mesh. Defaults to False.
        fixed: A boolean per-face mask of the cells the result must preserve, whatever the
            dilation would do to them — scipy's ``mask`` argument. ``None`` leaves every
            face free to change. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with the dilated mask.
    """
    var = self._facade_variable("binary_dilation", variable_name)
    grown = _graph.binary_dilation(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data).astype(bool),
        iterations=iterations,
        border_value=border_value,
        fixed=fixed,
    )
    return self._rewrap(var, grown)

binary_erosion(variable_name=None, *, iterations=1, border_value=False, fixed=None) #

Shrink a boolean face mask away from its boundary.

Parameters:

Name Type Description Default
variable_name str | None

The boolean face variable to erode, or None for the only one.

None
iterations int

How many times to shrink. Defaults to 1.

1
border_value bool

What lies outside the mesh. Defaults to False, which erodes the boundary; pass True to erode only the interior.

False
fixed ndarray | None

A boolean per-face mask of the cells the result must preserve, whatever the erosion would do to them — scipy's mask argument. None leaves every face free to change. Defaults to None.

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with the eroded mask.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def binary_erosion(
    self,
    variable_name: str | None = None,
    *,
    iterations: int = 1,
    border_value: bool = False,
    fixed: np.ndarray | None = None,
) -> Any:
    """Shrink a boolean face mask away from its boundary.

    Args:
        variable_name: The boolean face variable to erode, or ``None`` for the only one.
        iterations: How many times to shrink. Defaults to 1.
        border_value: What lies outside the mesh. Defaults to False, which erodes the
            boundary; pass True to erode only the interior.
        fixed: A boolean per-face mask of the cells the result must preserve, whatever the
            erosion would do to them — scipy's ``mask`` argument. ``None`` leaves every
            face free to change. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with the eroded mask.
    """
    var = self._facade_variable("binary_erosion", variable_name)
    shrunk = _graph.binary_erosion(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data).astype(bool),
        iterations=iterations,
        border_value=border_value,
        fixed=fixed,
    )
    return self._rewrap(var, shrunk)

to_location(location, variable_name=None) #

Remap a variable onto another facet of the mesh.

Averages the values of the contributing elements, so a face field asked for on the nodes becomes each node's mean of the faces around it.

Parameters:

Name Type Description Default
location str

The facet to remap onto — "node", "edge" or "face".

required
variable_name str | None

The variable to remap, or None for the only one.

None

Returns:

Name Type Description
UgridDataset Any

A new dataset whose variable sits on location.

Raises:

Type Description
ValueError

An unknown location, or a remap the kernel does not offer.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def to_location(self, location: str, variable_name: str | None = None) -> Any:
    """Remap a variable onto another facet of the mesh.

    Averages the values of the contributing elements, so a face field asked for on the
    nodes becomes each node's mean of the faces around it.

    Args:
        location: The facet to remap onto — ``"node"``, ``"edge"`` or ``"face"``.
        variable_name: The variable to remap, or ``None`` for the only one.

    Returns:
        UgridDataset: A new dataset whose variable sits on ``location``.

    Raises:
        ValueError: An unknown ``location``, or a remap the kernel does not offer.
    """
    var = self._facade_variable("to_location", variable_name)
    remap = {"node": _graph.to_node, "edge": _graph.to_edge, "face": _graph.to_face}
    if location not in remap:
        raise ValueError(
            f"to_location: location must be one of {sorted(remap)}, got {location!r}."
        )
    if var.location == location:
        # Already there. The averaging kernels only accept the two *other* facets as a
        # source, so without this an identity remap failed with "source must be 'node' or
        # 'edge'" -- a confusing answer to a request that is trivially already satisfied.
        return self._rebuild(dict(self._data_variables))  # type: ignore[attr-defined]
    values = remap[location](
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        source=var.location,
    )
    moved = var.with_data(np.asarray(values))
    moved.location = location
    # An element with no contributor (an orphan node, say) averages to NaN, so the remapped
    # variable has to declare NaN as its no-data value -- the same reasoning the regrid facade
    # already applies. Otherwise `to_file` writes those NaNs under the old `_FillValue`.
    # Through the same check `_rewrap` applies, rather than declared unconditionally.
    # `graph._average_over` answers float64 today, so NaN is always representable -- but a
    # future integer-preserving remap would reintroduce exactly the defect `_rewrap` guards.
    moved_values = np.asarray(moved.data)
    if _representable(float("nan"), moved_values.dtype):
        moved.nodata = float("nan")
    if moved.dimensions:
        # The element axis is the last dimension, by the mesh-variable invariant. Renaming it
        # to the new facet matters because a file-read variable carries real dimension names
        # and the xarray bridge prefers them: leaving the old facet's name on an axis that now
        # has the new facet's length makes the export fail on conflicting dimension sizes.
        mesh_name = self.mesh_name  # type: ignore[attr-defined]
        moved.dimensions = moved.dimensions[:-1] + (
            f"{mesh_name}_n{location.capitalize()}s",
        )
    new_vars = dict(self._data_variables)  # type: ignore[attr-defined]
    new_vars[var.name] = moved
    return self._rebuild(new_vars)  # type: ignore[attr-defined]

fill_na_spatial(variable_name=None, *, max_distance=None) #

Fill each gap from the nearest valid element in space.

Where :meth:interpolate_na fills along time, this fills across the mesh: a gap takes the value of the closest element that has one.

Parameters:

Name Type Description Default
variable_name str | None

The variable to fill, or None for the only one.

None
max_distance float | None

Leave a gap unfilled when no valid element is this close. None (the default) is unbounded.

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with the gaps filled.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def fill_na_spatial(
    self, variable_name: str | None = None, *, max_distance: float | None = None
) -> Any:
    """Fill each gap from the nearest valid element in space.

    Where :meth:`interpolate_na` fills along time, this fills across the mesh: a gap takes
    the value of the closest element that has one.

    Args:
        variable_name: The variable to fill, or ``None`` for the only one.
        max_distance: Leave a gap unfilled when no valid element is this close. ``None``
            (the default) is unbounded.

    Returns:
        UgridDataset: A new dataset with the gaps filled.
    """
    var = self._facade_variable("fill_na_spatial", variable_name)
    filled = _fill.fill_na_spatial(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        var.location,
        max_distance=max_distance,
    )
    return self._rewrap(var, filled)

laplace_interpolate(variable_name=None, *, use_weights=True, direct_solve=False) #

Fill the interior gaps by solving Laplace's equation over the mesh.

The valid values are the boundary condition and each gap becomes the smooth solution between them — a better hole-filler than nearest when the field varies smoothly.

Parameters:

Name Type Description Default
variable_name str | None

The variable to fill, or None for the only one.

None
use_weights bool

Weight the graph Laplacian by inverse distance. Defaults to True.

True
direct_solve bool

Solve directly rather than iteratively. Defaults to False.

False

Returns:

Name Type Description
UgridDataset Any

A new dataset with the interior gaps filled.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def laplace_interpolate(
    self,
    variable_name: str | None = None,
    *,
    use_weights: bool = True,
    direct_solve: bool = False,
) -> Any:
    """Fill the interior gaps by solving Laplace's equation over the mesh.

    The valid values are the boundary condition and each gap becomes the smooth solution
    between them — a better hole-filler than nearest when the field varies smoothly.

    Args:
        variable_name: The variable to fill, or ``None`` for the only one.
        use_weights: Weight the graph Laplacian by inverse distance. Defaults to True.
        direct_solve: Solve directly rather than iteratively. Defaults to False.

    Returns:
        UgridDataset: A new dataset with the interior gaps filled.
    """
    var = self._facade_variable("laplace_interpolate", variable_name)
    filled = _fill.laplace_interpolate(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        var.location,
        use_weights=use_weights,
        direct_solve=direct_solve,
    )
    return self._rewrap(var, filled)

polygonize(variable_name=None, *, decimals=None) #

Dissolve adjacent faces of equal value into polygons.

Parameters:

Name Type Description Default
variable_name str | None

The face variable to dissolve by, or None for the only one.

None
decimals int | None

Round to this many decimals before grouping, for approximate equality.

None

Returns:

Type Description
Any

geopandas.GeoDataFrame: One row per merged region, with its value and geometry.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def polygonize(
    self, variable_name: str | None = None, *, decimals: int | None = None
) -> Any:
    """Dissolve adjacent faces of equal value into polygons.

    Args:
        variable_name: The face variable to dissolve by, or ``None`` for the only one.
        decimals: Round to this many decimals before grouping, for approximate equality.

    Returns:
        geopandas.GeoDataFrame: One row per merged region, with its value and geometry.
    """
    var = self._facade_variable("polygonize", variable_name)
    return _vector_ops.polygonize(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        decimals=decimals,
        crs=self.crs,  # type: ignore[attr-defined]
    )

sample_line(line, variable_name=None) #

Sample a variable along a line, ordered by distance along it.

One sample per crossing, at the midpoint of each part of the line-face intersection. A line that leaves a face and re-enters it is sampled once per entry, so face_indices can repeat -- see :func:pyramids.netcdf.ugrid.vector_ops.sample_line.

Parameters:

Name Type Description Default
line Any

A shapely LineString, or a sequence of coordinates.

required
variable_name str | None

The variable to sample, or None for the only one.

None

Returns:

Name Type Description
tuple Any

(distances, values, face_indices), one entry per crossing in

Any

along-line order. face_indices is not unique when the line re-enters a face.

Raises:

Type Description
ValueError

variable_name is None while the dataset holds no variable or more than one, or the variable's last axis does not match n_face.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def sample_line(self, line: Any, variable_name: str | None = None) -> Any:
    """Sample a variable along a line, ordered by distance along it.

    One sample per *crossing*, at the midpoint of each part of the line-face intersection.
    A line that leaves a face and re-enters it is sampled once per entry, so
    ``face_indices`` can repeat -- see :func:`pyramids.netcdf.ugrid.vector_ops.sample_line`.

    Args:
        line: A shapely ``LineString``, or a sequence of coordinates.
        variable_name: The variable to sample, or ``None`` for the only one.

    Returns:
        tuple: ``(distances, values, face_indices)``, one entry per crossing in
        along-line order. ``face_indices`` is not unique when the line re-enters a face.

    Raises:
        ValueError: ``variable_name`` is ``None`` while the dataset holds no variable or
            more than one, or the variable's last axis does not match ``n_face``.
    """
    var = self._facade_variable("sample_line", variable_name)
    return _vector_ops.sample_line(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        line,
    )

burn(geometry, value, *, name='burned', fill=float('nan'), all_touched=True) #

Burn vector geometry onto the faces as a new variable.

The mesh analogue of rasterising a vector layer: every face the geometry covers takes value, the rest take fill.

Parameters:

Name Type Description Default
geometry Any

A shapely geometry, GeoDataFrame, FeatureCollection, or iterable of them.

required
value float

The value burned into the covered faces.

required
name str

The new variable's name. Defaults to "burned".

'burned'
fill float

The value for the faces the geometry misses. Defaults to NaN.

float('nan')
all_touched bool

Burn every face the geometry touches, rather than only those whose centroid falls inside. Defaults to True.

True

Returns:

Name Type Description
UgridDataset Any

A new dataset carrying the burned variable.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def burn(
    self,
    geometry: Any,
    value: float,
    *,
    name: str = "burned",
    fill: float = float("nan"),
    all_touched: bool = True,
) -> Any:
    """Burn vector geometry onto the faces as a new variable.

    The mesh analogue of rasterising a vector layer: every face the geometry covers takes
    ``value``, the rest take ``fill``.

    Args:
        geometry: A shapely geometry, GeoDataFrame, FeatureCollection, or iterable of them.
        value: The value burned into the covered faces.
        name: The new variable's name. Defaults to ``"burned"``.
        fill: The value for the faces the geometry misses. Defaults to NaN.
        all_touched: Burn every face the geometry touches, rather than only those whose
            centroid falls inside. Defaults to True.

    Returns:
        UgridDataset: A new dataset carrying the burned variable.
    """
    values = _vector_ops.burn(
        self._mesh,  # type: ignore[attr-defined]
        geometry,
        value,
        fill=fill,
        all_touched=all_touched,
    )
    # Declare the fill as no-data only when it is NaN. A NaN fill means "untouched", so
    # naming it is what makes an untouched face distinguishable once written. An explicit
    # numeric fill is a value the caller chose, not a sentinel: `burn(geom, 1.0, fill=0.0)`
    # is the 0/1 mask idiom, and declaring 0.0 as missing made `dropna` and every `skipna`
    # reduction discard the unburned faces.
    burned = np.asarray(values)
    declared = float(fill) if np.isnan(fill) else None
    return self.with_variable(  # type: ignore[attr-defined]
        name, burned, location="face", nodata=declared
    )

rasterize_like(reference, variable_name=None, *, method='nearest', nodata=-9999.0, max_distance=None) #

Interpolate a variable onto an existing raster's grid.

Where :meth:to_dataset builds its own grid from a cell size, this snaps to the geotransform, shape and CRS of a raster you already have, so the result is co-registered with it.

Parameters:

Name Type Description Default
reference Any

The raster whose grid to match (a pyramids Dataset / NetCDF).

required
variable_name str | None

The variable to interpolate, or None for the only one.

None
method str

"nearest", "linear" or "idw". Defaults to "nearest".

'nearest'
nodata float

The value for cells the mesh does not cover.

-9999.0
max_distance float | None

How far a "nearest" / "idw" sample may reach. None uses twice the longer of the reference's two cell edges. Defaults to None.

None

Returns:

Name Type Description
Dataset Any

A raster on reference's grid.

Raises:

Type Description
ValueError

An unknown method, or the mesh declares an EPSG while reference declares no CRS to reproject into.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def rasterize_like(
    self,
    reference: Any,
    variable_name: str | None = None,
    *,
    method: str = "nearest",
    nodata: float = -9999.0,
    max_distance: float | None = None,
) -> Any:
    """Interpolate a variable onto an existing raster's grid.

    Where :meth:`to_dataset` builds its own grid from a cell size, this snaps to the
    geotransform, shape and CRS of a raster you already have, so the result is
    co-registered with it.

    Args:
        reference: The raster whose grid to match (a pyramids ``Dataset`` / ``NetCDF``).
        variable_name: The variable to interpolate, or ``None`` for the only one.
        method: ``"nearest"``, ``"linear"`` or ``"idw"``. Defaults to ``"nearest"``.
        nodata: The value for cells the mesh does not cover.
        max_distance: How far a ``"nearest"`` / ``"idw"`` sample may reach. ``None`` uses
            twice the longer of the reference's two cell edges. Defaults to ``None``.

    Returns:
        Dataset: A raster on ``reference``'s grid.

    Raises:
        ValueError: An unknown ``method``, or the mesh declares an EPSG while
            ``reference`` declares no CRS to reproject into.
    """
    var = self._facade_variable("rasterize_like", variable_name)
    return _regrid.rasterize_like(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        reference,
        location=var.location,
        method=method,
        nodata=nodata,
        source_epsg=self.epsg,  # type: ignore[attr-defined]
        max_distance=max_distance,
    )

interp_time(new_times, *, method='linear', bounds='nan') #

Interpolate every temporal variable onto new time coordinates.

Distinct from :meth:interpolate_na, which fills gaps on the existing axis: this relabels the axis, resampling the series onto the times you ask for.

Parameters:

Name Type Description Default
new_times Any

The time coordinates to interpolate onto.

required
method str

"linear" or "nearest". Defaults to "linear". (Not every scipy.interpolate.interp1d kind: the kernel accepts these two.)

'linear'
bounds str

What a label outside the existing axis answers -- "nan" for NaN, or "clamp" to hold the first/last step's value. Defaults to "nan".

'nan'

Returns:

Name Type Description
UgridDataset Any

A new dataset on the requested time coordinates.

Raises:

Type Description
ValueError

No variable has a time dimension; method is neither "linear" nor "nearest"; bounds is neither "nan" nor "clamp"; or the time coordinates are not numeric.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def interp_time(
    self, new_times: Any, *, method: str = "linear", bounds: str = "nan"
) -> Any:
    """Interpolate every temporal variable onto new time coordinates.

    Distinct from :meth:`interpolate_na`, which fills gaps on the existing axis: this
    *relabels* the axis, resampling the series onto the times you ask for.

    Args:
        new_times: The time coordinates to interpolate onto.
        method: ``"linear"`` or ``"nearest"``. Defaults to ``"linear"``. (Not every
            ``scipy.interpolate.interp1d`` kind: the kernel accepts these two.)
        bounds: What a label outside the existing axis answers -- ``"nan"`` for NaN, or
            ``"clamp"`` to hold the first/last step's value. Defaults to ``"nan"``.

    Returns:
        UgridDataset: A new dataset on the requested time coordinates.

    Raises:
        ValueError: No variable has a time dimension; ``method`` is neither ``"linear"``
            nor ``"nearest"``; ``bounds`` is neither ``"nan"`` nor ``"clamp"``; or the time
            coordinates are not numeric.
    """
    stamps = self._time_coords("interp_time")  # type: ignore[attr-defined]
    targets = list(np.atleast_1d(np.asarray(new_times)))
    # `new_times` goes through the same converter as the existing axis, so a date target
    # is measured on the same scale as the dated coordinates it sits between. Casting it
    # with a bare `astype("float64")` was what made a `Timestamp` target unusable even
    # once the axis itself could be read.
    numeric_targets = _numeric_stamps(targets)
    new_vars: dict[str, Any] = {}
    for name, var in self._data_variables.items():  # type: ignore[attr-defined]
        if not var.has_time:
            new_vars[name] = var
            continue
        moved = _regrid.interp_time(
            _numeric_stamps(stamps),
            np.asarray(var.data),
            numeric_targets,
            method=method,
            axis=cast("int", var.time_index),
            bounds=bounds,
        )
        new_var = var.with_data(np.asarray(moved))
        new_var.attributes = {**var.attributes, "time_values": targets}
        new_vars[name] = new_var
    return self._rebuild(new_vars)  # type: ignore[attr-defined]

regrid(target, *, method='overlap', variable_name=None) #

Regrid a variable onto another mesh.

Parameters:

Name Type Description Default
target Any

The destination UgridDataset (its mesh is the target).

required
method str

"overlap" (area-weighted mean), "conservative" (integral preserving), "centroid" or "barycentric". Defaults to "overlap".

'overlap'
variable_name str | None

The variable to regrid, or None for the only one.

None

Returns:

Name Type Description
UgridDataset Any

target's mesh carrying the regridded variable.

Raises:

Type Description
ValueError

An unknown method; the variable does not sit on faces (only "face" source data is weighted); or variable_name is None while the dataset holds no variable or more than one.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def regrid(
    self, target: Any, *, method: str = "overlap", variable_name: str | None = None
) -> Any:
    """Regrid a variable onto another mesh.

    Args:
        target: The destination ``UgridDataset`` (its mesh is the target).
        method: ``"overlap"`` (area-weighted mean), ``"conservative"`` (integral
            preserving), ``"centroid"`` or ``"barycentric"``. Defaults to ``"overlap"``.
        variable_name: The variable to regrid, or ``None`` for the only one.

    Returns:
        UgridDataset: ``target``'s mesh carrying the regridded variable.

    Raises:
        ValueError: An unknown ``method``; the variable does not sit on faces (only
            ``"face"`` source data is weighted); or ``variable_name`` is ``None`` while the
            dataset holds no variable or more than one.
    """
    var = self._facade_variable("regrid", variable_name)
    regridder = _regrid.Regridder(
        self._mesh,  # type: ignore[attr-defined]
        target.mesh,
        method=method,
        source_location=var.location,
    )
    values = regridder.regrid(np.asarray(var.data))
    # A target element the source does not cover comes back NaN, so the regridded variable
    # has to declare NaN as its no-data value -- otherwise `to_file` writes those NaNs with
    # no `_FillValue` and a reader cannot tell them from data.
    return target.with_variable(
        var.name, np.asarray(values), location="face", nodata=float("nan")
    )

to_xarray() #

Hand the mesh and its variables to xarray, in the UGRID-CF encoding.

xarray is a peer dependency, imported only here (as the raster :meth:pyramids.netcdf.NetCDF.to_xarray does), so nothing here imports it at module scope. Note the parent pyramids.netcdf package does currently pull xarray and dask at import time for unrelated reasons, so that cost is not avoided in practice yet.

Returns:

Type Description
Any

xarray.Dataset: The mesh's UGRID-CF variables plus the data variables.

Raises:

Type Description
OptionalPackageDoesNotExist

xarray is not installed.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def to_xarray(self) -> Any:
    """Hand the mesh and its variables to xarray, in the UGRID-CF encoding.

    xarray is a **peer dependency**, imported only here (as the raster
    :meth:`pyramids.netcdf.NetCDF.to_xarray` does), so nothing here imports it at module
    scope. Note the parent ``pyramids.netcdf`` package does currently pull xarray and dask
    at import time for unrelated reasons, so that cost is not avoided in practice yet.

    Returns:
        xarray.Dataset: The mesh's UGRID-CF variables plus the data variables.

    Raises:
        OptionalPackageDoesNotExist: xarray is not installed.
    """
    return _interop.to_xarray(
        self._mesh,  # type: ignore[attr-defined]
        self._data_variables,  # type: ignore[attr-defined]
        # The dataset's own topology name, not the default: exporting a mesh called
        # anything else wrote its topology as "mesh2d" while the data variables kept
        # their own element dimension, leaving two unrelated dimensions in one file.
        mesh_name=self.mesh_name,  # type: ignore[attr-defined]
        crs_wkt=self.crs_wkt,  # type: ignore[attr-defined]
        volume_topology=self._volume_topology,  # type: ignore[attr-defined]
    )

to_zarr(store, **kwargs) #

Write the mesh and its variables to a zarr store, through xarray.

Parameters:

Name Type Description Default
store Any

The zarr store (a path or a mapping).

required
**kwargs Any

Passed to xarray.Dataset.to_zarr.

{}

Returns:

Type Description
Any

The value xarray.Dataset.to_zarr returns.

Raises:

Type Description
OptionalPackageDoesNotExist

xarray or zarr is not installed.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def to_zarr(self, store: Any, **kwargs: Any) -> Any:
    """Write the mesh and its variables to a zarr store, through xarray.

    Args:
        store: The zarr store (a path or a mapping).
        **kwargs: Passed to ``xarray.Dataset.to_zarr``.

    Returns:
        The value ``xarray.Dataset.to_zarr`` returns.

    Raises:
        OptionalPackageDoesNotExist: xarray or zarr is not installed.
    """
    return _interop.to_zarr(
        self._mesh,  # type: ignore[attr-defined]
        self._data_variables,  # type: ignore[attr-defined]
        store,
        mesh_name=self.mesh_name,  # type: ignore[attr-defined]
        crs_wkt=self.crs_wkt,  # type: ignore[attr-defined]
        **kwargs,
    )

fillna(value, variable_name=None) #

Replace missing values with value.

Parameters:

Name Type Description Default
value Any

The fill value.

required
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with missing values replaced.

See Also

isnull: Boolean mask of missing positions. fill_na_spatial: Fill gaps from the nearest valid spatial element.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def fillna(self, value: Any, variable_name: str | None = None) -> Any:
    """Replace missing values with *value*.

    Args:
        value: The fill value.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with missing values replaced.

    See Also:
        isnull: Boolean mask of missing positions.
        fill_na_spatial: Fill gaps from the nearest valid spatial
            element.

    """
    var = self._facade_variable("fillna", variable_name)
    result = _array_ops.fillna(np.asarray(var.data), value, var.nodata)
    return self._rewrap(var, result)

isnull(variable_name=None) #

Boolean mask of missing positions.

Parameters:

Name Type Description Default
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with boolean data.

See Also

notnull: Inverse mask (non-missing positions). fillna: Replace missing values with a constant.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def isnull(self, variable_name: str | None = None) -> Any:
    """Boolean mask of missing positions.

    Args:
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with boolean data.

    See Also:
        notnull: Inverse mask (non-missing positions).
        fillna: Replace missing values with a constant.

    """
    var = self._facade_variable("isnull", variable_name)
    result = _array_ops.isnull(np.asarray(var.data), var.nodata)
    return self._rewrap(var, result)

notnull(variable_name=None) #

Boolean mask of non-missing positions.

Parameters:

Name Type Description Default
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with boolean data.

See Also

isnull: Inverse mask (missing positions).

Source code in src/pyramids/netcdf/ugrid/_facades.py
def notnull(self, variable_name: str | None = None) -> Any:
    """Boolean mask of non-missing positions.

    Args:
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with boolean data.

    See Also:
        isnull: Inverse mask (missing positions).

    """
    var = self._facade_variable("notnull", variable_name)
    result = _array_ops.notnull(np.asarray(var.data), var.nodata)
    return self._rewrap(var, result)

clip_values(lower, upper, variable_name=None) #

Clamp variable values to [lower, upper].

Named clip_values to avoid collision with the spatial :meth:~pyramids.netcdf.ugrid.dataset.UgridDataset.clip method.

Parameters:

Name Type Description Default
lower Any

Minimum allowed value.

required
upper Any

Maximum allowed value.

required
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with clamped values.

See Also

round: Round values to a number of decimal places.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def clip_values(
    self, lower: Any, upper: Any, variable_name: str | None = None
) -> Any:
    """Clamp variable values to ``[lower, upper]``.

    Named ``clip_values`` to avoid collision with the spatial
    :meth:`~pyramids.netcdf.ugrid.dataset.UgridDataset.clip` method.

    Args:
        lower: Minimum allowed value.
        upper: Maximum allowed value.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with clamped values.

    See Also:
        round: Round values to a number of decimal places.

    """
    var = self._facade_variable("clip_values", variable_name)
    result = _array_ops.clip_values(np.asarray(var.data), lower, upper)
    return self._rewrap(var, result)

round(decimals=0, variable_name=None) #

Round variable values to decimals decimal places.

Parameters:

Name Type Description Default
decimals int

Number of decimal places.

0
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with rounded values.

See Also

clip_values: Clamp values to a range.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def round(self, decimals: int = 0, variable_name: str | None = None) -> Any:
    """Round variable values to *decimals* decimal places.

    Args:
        decimals: Number of decimal places.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with rounded values.

    See Also:
        clip_values: Clamp values to a range.

    """
    var = self._facade_variable("round", variable_name)
    result = _array_ops.round_values(np.asarray(var.data), decimals)
    return self._rewrap(var, result)

astype(dtype, variable_name=None) #

Cast variable values to a different dtype.

Parameters:

Name Type Description Default
dtype Any

Target numpy dtype.

required
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with the new dtype.

See Also

round: Round floating-point values before an integer cast.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def astype(self, dtype: Any, variable_name: str | None = None) -> Any:
    """Cast variable values to a different dtype.

    Args:
        dtype: Target numpy dtype.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with the new dtype.

    See Also:
        round: Round floating-point values before an integer cast.

    """
    var = self._facade_variable("astype", variable_name)
    result = _array_ops.astype_values(np.asarray(var.data), dtype)
    return self._rewrap(var, result)

where(cond, other=np.nan, variable_name=None) #

Keep the elements cond selects and mask the rest (issue #1375).

The mesh counterpart of the raster where. A nodata / NaN element is never selected — there is no value there to keep — so it goes to other whatever cond says, leaving the result with one masking convention rather than two.

The per-timestep active mask (:attr:~pyramids.netcdf.ugrid.models.MeshVariable.active) is not applied here. Keeping "dry" distinct from "missing" is the whole point of that field (issue #1331), so activity-aware masking is something a caller composes explicitly: ds.where(ds.active_mask(name) & (values > 0)).

Parameters:

Name Type Description Default
cond Any

A boolean array broadcastable to the variable's values.

required
other Any

What an unselected element holds. Defaults to NaN.

nan
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with the unselected elements masked.

See Also

clip_values: Clamp values to a range instead of masking outside it. masked_values: Apply the active mask to the values, on demand.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def where(
    self,
    cond: Any,
    other: Any = np.nan,
    variable_name: str | None = None,
) -> Any:
    """Keep the elements ``cond`` selects and mask the rest (issue #1375).

    The mesh counterpart of the raster ``where``. A ``nodata`` / NaN element is never
    selected — there is no value there to keep — so it goes to ``other`` whatever ``cond``
    says, leaving the result with one masking convention rather than two.

    The per-timestep active mask (:attr:`~pyramids.netcdf.ugrid.models.MeshVariable.active`)
    is **not** applied here. Keeping "dry" distinct from "missing" is the whole point of
    that field (issue #1331), so activity-aware masking is something a caller composes
    explicitly: ``ds.where(ds.active_mask(name) & (values > 0))``.

    Args:
        cond: A boolean array broadcastable to the variable's values.
        other: What an unselected element holds. Defaults to NaN.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with the unselected elements masked.

    See Also:
        clip_values: Clamp values to a range instead of masking outside it.
        masked_values: Apply the active mask to the values, on demand.
    """
    var = self._facade_variable("where", variable_name)
    result = _array_ops.where_values(np.asarray(var.data), cond, other, var.nodata)
    # With a non-NaN `other`, every no-data element is overwritten by it, so the result no
    # longer uses the source's sentinel to mark anything and declaring it would claim a
    # marker that is now an ordinary value. With the default NaN fill the gaps stay
    # missing, so the sentinel still describes them.
    overwrites_gaps = other is not None and not (
        isinstance(other, float) and np.isnan(other)
    )
    return self._rewrap(var, result, keep_nodata=not overwrites_gaps)

apply(func, variable_name=None) #

Apply func to every element of a variable (issue #1375).

The mesh counterpart of the raster apply. func receives the whole array, so a numpy ufunc runs vectorised rather than once per element. The shape must survive, since the result still has to line up with the mesh elements it describes.

Parameters:

Name Type Description Default
func Any

A callable taking and returning an array of the same shape.

required
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset carrying the transformed values.

Raises:

Type Description
ValueError

func changed the array shape.

See Also

astype: Cast values to another dtype. round: Round values to a number of decimal places.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def apply(self, func: Any, variable_name: str | None = None) -> Any:
    """Apply ``func`` to every element of a variable (issue #1375).

    The mesh counterpart of the raster ``apply``. ``func`` receives the whole array, so a
    numpy ufunc runs vectorised rather than once per element. The shape must survive, since
    the result still has to line up with the mesh elements it describes.

    Args:
        func: A callable taking and returning an array of the same shape.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset carrying the transformed values.

    Raises:
        ValueError: ``func`` changed the array shape.

    See Also:
        astype: Cast values to another dtype.
        round: Round values to a number of decimal places.
    """
    var = self._facade_variable("apply", variable_name)
    result = _array_ops.apply_values(np.asarray(var.data), func)
    return self._rewrap(var, result)

get_histogram(bins=256, value_range=None, variable_name=None) #

The variable's value distribution as data (issue #1375).

The mesh counterpart of the raster get_histogram. :meth:plot_histogram could already draw the distribution but gave no way to obtain it; both mask no-data through the same helper, so these counts describe exactly the samples those bars show.

Parameters:

Name Type Description Default
bins int

Number of equal-width bins. Defaults to 256.

256
value_range tuple[float, float] | None

(low, high) to bin within, or None to span the data.

None
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
tuple ndarray

(counts, edges) -- per-bin counts and the bins + 1 edges, in the

ndarray

variable's own units.

Raises:

Type Description
ValueError

Nothing survives the no-data masking, so there is no distribution.

See Also

plot_histogram: The same distribution, drawn. summary: Per-variable min / max / mean / std over the whole mesh.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def get_histogram(
    self,
    bins: int = 256,
    value_range: tuple[float, float] | None = None,
    variable_name: str | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    """The variable's value distribution as data (issue #1375).

    The mesh counterpart of the raster ``get_histogram``. :meth:`plot_histogram` could
    already *draw* the distribution but gave no way to obtain it; both mask no-data through
    the same helper, so these counts describe exactly the samples those bars show.

    Args:
        bins: Number of equal-width bins. Defaults to 256.
        value_range: ``(low, high)`` to bin within, or ``None`` to span the data.
        variable_name: Variable to act on (default: the only one).

    Returns:
        tuple: ``(counts, edges)`` -- per-bin counts and the ``bins + 1`` edges, in the
        variable's own units.

    Raises:
        ValueError: Nothing survives the no-data masking, so there is no distribution.

    See Also:
        plot_histogram: The same distribution, drawn.
        summary: Per-variable min / max / mean / std over the whole mesh.
    """
    var = self._facade_variable("get_histogram", variable_name)
    return _analysis.histogram(np.asarray(var.data), var.nodata, bins, value_range)

isin(test_values, variable_name=None) #

Boolean mask where variable values are in test_values.

Parameters:

Name Type Description Default
test_values Any

Values to test membership against.

required
variable_name str | None

Variable to act on (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with boolean data.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def isin(self, test_values: Any, variable_name: str | None = None) -> Any:
    """Boolean mask where variable values are in *test_values*.

    Args:
        test_values: Values to test membership against.
        variable_name: Variable to act on (default: the only one).

    Returns:
        UgridDataset: A new dataset with boolean data.
    """
    var = self._facade_variable("isin", variable_name)
    result = _array_ops.isin_values(np.asarray(var.data), test_values)
    return self._rewrap(var, result)

domain_area() #

Total area of the mesh domain.

Returns:

Name Type Description
float float

Sum of all face areas in the mesh's coordinate units squared.

See Also

count_domain_cells: Count of active faces rather than their total area.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def domain_area(self) -> float:
    """Total area of the mesh domain.

    Returns:
        float: Sum of all face areas in the mesh's coordinate
            units squared.

    See Also:
        count_domain_cells: Count of active faces rather than
            their total area.
    """
    return float(self._mesh.face_areas.sum())  # type: ignore[attr-defined]

count_domain_cells(variable_name=None) #

Number of active (non-masked) mesh faces.

When the variable carries no active mask, all faces are counted.

Parameters:

Name Type Description Default
variable_name str | None

Variable whose active mask to consult. None counts all faces.

None

Returns:

Name Type Description
int int

Active face count.

See Also

domain_area: Total area rather than face count.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def count_domain_cells(self, variable_name: str | None = None) -> int:
    """Number of active (non-masked) mesh faces.

    When the variable carries no active mask, all faces are counted.

    Args:
        variable_name: Variable whose active mask to consult.
            ``None`` counts all faces.

    Returns:
        int: Active face count.

    See Also:
        domain_area: Total area rather than face count.

    """
    result = int(self._mesh.n_face)  # type: ignore[attr-defined]
    if variable_name is not None:
        mask = self.active_mask(variable_name)  # type: ignore[attr-defined]
        if mask is not None:
            if mask.ndim > 1:
                mask = mask[-1]
            result = int(np.count_nonzero(mask))
    return result

extract(x, y, variable_name=None) #

Sample variable values at arbitrary (x, y) coordinates.

Uses an STRtree spatial index to locate the containing face for each query point.

Parameters:

Name Type Description Default
x Any

Query x-coordinates (scalar or array).

required
y Any

Query y-coordinates (scalar or array).

required
variable_name str | None

Variable to extract (default: the only one).

None

Returns:

Type Description
Any

numpy array of extracted values. Points outside the mesh

Any

get NaN.

See Also

sample_random: Draw spatially random samples instead of querying specific coordinates. sample: Interpolated point sampling (existing method on UgridDataset).

Source code in src/pyramids/netcdf/ugrid/_facades.py
def extract(
    self,
    x: Any,
    y: Any,
    variable_name: str | None = None,
) -> Any:
    """Sample variable values at arbitrary (x, y) coordinates.

    Uses an STRtree spatial index to locate the containing face
    for each query point.

    Args:
        x: Query x-coordinates (scalar or array).
        y: Query y-coordinates (scalar or array).
        variable_name: Variable to extract (default: the only one).

    Returns:
        numpy array of extracted values.  Points outside the mesh
        get ``NaN``.

    See Also:
        sample_random: Draw spatially random samples instead of
            querying specific coordinates.
        sample: Interpolated point sampling (existing method on
            UgridDataset).
    """
    var = self._facade_variable("extract", variable_name)
    result = _analysis.extract_points(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        np.atleast_1d(np.asarray(x, dtype=float)),
        np.atleast_1d(np.asarray(y, dtype=float)),
        var.location,
    )
    return result

sample_random(n, variable_name=None, seed=None) #

Draw n spatially random samples from the mesh domain.

Parameters:

Name Type Description Default
n int

Number of samples.

required
variable_name str | None

Variable to sample (default: the only one).

None
seed int | None

RNG seed for reproducibility.

None

Returns:

Type Description
tuple

(x, y, values) — arrays of length n.

See Also

extract: Sample at specific coordinates rather than random ones.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def sample_random(
    self,
    n: int,
    variable_name: str | None = None,
    seed: int | None = None,
) -> tuple:
    """Draw *n* spatially random samples from the mesh domain.

    Args:
        n: Number of samples.
        variable_name: Variable to sample (default: the only one).
        seed: RNG seed for reproducibility.

    Returns:
        ``(x, y, values)`` — arrays of length *n*.

    See Also:
        extract: Sample at specific coordinates rather than random
            ones.

    """
    var = self._facade_variable("sample_random", variable_name)
    result = _analysis.sample_random(
        self._mesh,  # type: ignore[attr-defined]
        np.asarray(var.data),
        n,
        seed,
    )
    return result

contour(levels=None, variable_name=None) #

Generate contour lines from face/node values.

Parameters:

Name Type Description Default
levels Any

Contour levels (int for count, array for explicit).

None
variable_name str | None

Variable to contour (default: the only one).

None

Returns:

Type Description
Any

GeoDataFrame with contour LineString geometries and a

Any

level column.

Raises:

Type Description
ValueError

If the variable has more than one time step; select a single step first.

See Also

plot_histogram: Distribution of the same variable as a histogram.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def contour(
    self,
    levels: Any = None,
    variable_name: str | None = None,
) -> Any:
    """Generate contour lines from face/node values.

    Args:
        levels: Contour levels (int for count, array for explicit).
        variable_name: Variable to contour (default: the only one).

    Returns:
        GeoDataFrame with contour ``LineString`` geometries and a
        ``level`` column.

    Raises:
        ValueError: If the variable has more than one time step;
            select a single step first.

    See Also:
        plot_histogram: Distribution of the same variable as a
            histogram.

    """
    var = self._facade_variable("contour", variable_name)
    data = np.asarray(var.data)
    if data.ndim > 1:
        raise ValueError(
            "contour requires a single time step; select a time "
            "step first to reduce temporal data to 1-D."
        )
    result = _analysis.contour_lines(
        self._mesh,  # type: ignore[attr-defined]
        data,
        levels,
        var.location,
    )
    return result

plot_histogram(bins=15, variable_name=None, ax=None, **kwargs) #

Plot the distribution of a variable's values.

Delegates to cleopatra's HistogramGlyph.

Parameters:

Name Type Description Default
bins int

Number of histogram bins.

15
variable_name str | None

Variable to histogram (default: the only one).

None
ax Any

Existing matplotlib axes to draw into.

None
**kwargs Any

Forwarded to the glyph constructor.

{}

Returns:

Type Description
Any

(fig, ax, hist) from HistogramGlyph.histogram.

See Also

contour: Spatial contour extraction from the same variable.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def plot_histogram(
    self,
    bins: int = 15,
    variable_name: str | None = None,
    ax: Any = None,
    **kwargs: Any,
) -> Any:
    """Plot the distribution of a variable's values.

    Delegates to cleopatra's ``HistogramGlyph``.

    Args:
        bins: Number of histogram bins.
        variable_name: Variable to histogram (default: the only one).
        ax: Existing matplotlib axes to draw into.
        **kwargs: Forwarded to the glyph constructor.

    Returns:
        ``(fig, ax, hist)`` from ``HistogramGlyph.histogram``.

    See Also:
        contour: Spatial contour extraction from the same variable.

    """
    var = self._facade_variable("plot_histogram", variable_name)
    result = _analysis.plot_histogram(
        np.asarray(var.data), var.nodata, bins=bins, ax=ax, **kwargs
    )
    return result

proximity(target_faces) #

Graph distance from every face to the nearest target face.

Uses BFS over the face adjacency graph.

Parameters:

Name Type Description Default
target_faces Any

1-D array of face indices that are targets (distance zero).

required

Returns:

Type Description
Any

numpy array of per-face integer distances. -1 for

Any

faces in disconnected components with no target.

See Also

sieve: Remove small connected regions by area threshold.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def proximity(self, target_faces: Any) -> Any:
    """Graph distance from every face to the nearest target face.

    Uses BFS over the face adjacency graph.

    Args:
        target_faces: 1-D array of face indices that are targets
            (distance zero).

    Returns:
        numpy array of per-face integer distances.  ``-1`` for
        faces in disconnected components with no target.

    See Also:
        sieve: Remove small connected regions by area threshold.
    """
    return _graph.proximity(
        self._mesh,  # type: ignore[attr-defined]
        np.atleast_1d(np.asarray(target_faces, dtype=np.intp)),
    )

sieve(threshold, variable_name=None) #

Remove small connected regions below threshold faces.

Faces in a connected component smaller than threshold are blanked to NaN. Operates on the face adjacency graph.

Parameters:

Name Type Description Default
threshold int

Minimum component size (face count) to keep.

required
variable_name str | None

Variable to sieve (default: the only one).

None

Returns:

Name Type Description
UgridDataset Any

A new dataset with small-region faces replaced by NaN.

Raises:

Type Description
ValueError

If the variable has more than one time step; select a single step first.

See Also

proximity: Compute graph distances from target faces.

Source code in src/pyramids/netcdf/ugrid/_facades.py
def sieve(
    self,
    threshold: int,
    variable_name: str | None = None,
) -> Any:
    """Remove small connected regions below *threshold* faces.

    Faces in a connected component smaller than *threshold* are
    blanked to NaN.  Operates on the face adjacency graph.

    Args:
        threshold: Minimum component size (face count) to keep.
        variable_name: Variable to sieve (default: the only one).

    Returns:
        UgridDataset: A new dataset with small-region faces
            replaced by NaN.

    Raises:
        ValueError: If the variable has more than one time step;
            select a single step first.

    See Also:
        proximity: Compute graph distances from target faces.

    """
    var = self._facade_variable("sieve", variable_name)
    data = np.asarray(var.data)
    if data.ndim > 1:
        raise ValueError(
            "sieve requires a single time step; select a time "
            "step first to reduce temporal data to 1-D."
        )
    result = _graph.sieve(
        self._mesh,  # type: ignore[attr-defined]
        data,
        threshold,
    )
    return self._rewrap(var, result)

__init__(mesh, data_variables, global_attributes, topology_info=None, crs_wkt=None, file_name=None, volume_topology=None) #

Assemble a dataset from an already-built mesh and its variables.

The low-level constructor. Prefer :meth:read_file for a file, :meth:from_arrays for raw arrays, or one of the from_* bridges -- each of those builds the mesh and the metadata record and then calls this. It is also what every derivation (:meth:isel, :meth:reduce, :meth:copy, ...) calls through type(self)(...), which is how a subclass survives them.

Parameters:

Name Type Description Default
mesh Mesh2d

The topology the variables sit on.

required
data_variables dict[str, MeshVariable]

Mapping of variable name to :class:MeshVariable. Held by reference, not copied, so a caller must not mutate it afterwards.

required
global_attributes dict[str, Any]

The file-level attributes, e.g. Conventions.

required
topology_info MeshTopologyInfo | None

The record of the on-disk variable names and the declared topology dimension. None for a mesh built from arrays, where there are no file variables to name. Defaults to None.

None
crs_wkt str | None

WKT of the mesh CRS. None leaves the mesh unreferenced, and :attr:epsg then answers None. Defaults to None.

None
file_name str | None

The path this dataset was read from, carried through derivations so a :meth:to_file round trip and repr can name it. None for an in-memory mesh. Defaults to None.

None
volume_topology VolumeTopology | None

The ragged (per-column) vertical layering for a genuinely 3-D mesh — the map from faces to the flat volume axis that a location="volume" variable is indexed through (issue #1330). None (the default) for a 2-D mesh or a uniform-layer 3-D one, where the dense (layer, element) path applies and :attr:n_volume answers None.

None
Source code in src/pyramids/netcdf/ugrid/dataset.py
def __init__(
    self,
    mesh: Mesh2d,
    data_variables: dict[str, MeshVariable],
    global_attributes: dict[str, Any],
    topology_info: MeshTopologyInfo | None = None,
    crs_wkt: str | None = None,
    file_name: str | None = None,
    volume_topology: VolumeTopology | None = None,
):
    """Assemble a dataset from an already-built mesh and its variables.

    The low-level constructor. Prefer :meth:`read_file` for a file, :meth:`from_arrays`
    for raw arrays, or one of the ``from_*`` bridges -- each of those builds the mesh and
    the metadata record and then calls this. It is also what every derivation
    (:meth:`isel`, :meth:`reduce`, :meth:`copy`, ...) calls through ``type(self)(...)``,
    which is how a subclass survives them.

    Args:
        mesh: The topology the variables sit on.
        data_variables: Mapping of variable name to :class:`MeshVariable`. Held by
            reference, not copied, so a caller must not mutate it afterwards.
        global_attributes: The file-level attributes, e.g. ``Conventions``.
        topology_info: The record of the on-disk variable names and the declared
            topology dimension. ``None`` for a mesh built from arrays, where there are
            no file variables to name. Defaults to ``None``.
        crs_wkt: WKT of the mesh CRS. ``None`` leaves the mesh unreferenced, and
            :attr:`epsg` then answers ``None``. Defaults to ``None``.
        file_name: The path this dataset was read from, carried through derivations so a
            :meth:`to_file` round trip and ``repr`` can name it. ``None`` for an
            in-memory mesh. Defaults to ``None``.
        volume_topology: The ragged (per-column) vertical layering for a genuinely 3-D
            mesh — the map from faces to the flat ``volume`` axis that a
            ``location="volume"`` variable is indexed through (issue #1330). ``None`` (the
            default) for a 2-D mesh or a uniform-layer 3-D one, where the dense
            ``(layer, element)`` path applies and :attr:`n_volume` answers ``None``.
    """
    self._mesh = mesh
    self._data_variables = data_variables
    self._global_attributes = global_attributes
    self._topology_info = topology_info
    self._crs_wkt = crs_wkt
    self._file_name = file_name
    self._volume_topology = volume_topology
    self._cached_crs: Any = None

read_file(path, mesh_name=None, driver=None, lazy=True) classmethod #

Open a mesh file.

UGRID NetCDF is read here. Any other format — 2DM, Selafin, DFSU, XMDF, … — is read by a third-party driver registered into the pyramids.mesh_drivers entry-point group. A non-NetCDF suffix is dispatched by detection; a NetCDF suffix is read by the built-in reader first, and only a file that opens but carries no UGRID topology falls back to a driver claiming that suffix. Either way a successful UGRID read triggers no driver discovery, so a .nc read still pays nothing.

Resolution order:

  1. driver given — that driver, or an error. Never falls back.
  2. A /vsi path or a NetCDF suffix — the built-in UGRID reader. If a NetCDF-suffixed file opens but declares no UGRID topology, a registered driver claiming that suffix is tried before giving up, so 3Di, TUFLOW FV and other NetCDF-based formats are reachable; discovery runs only after the built-in read has already failed.
  3. Otherwise a registered driver claiming the suffix whose can_open accepts the file.
  4. Nothing claimed it — the built-in reader anyway, so a NetCDF file under an unusual suffix still opens exactly as it always did.
  5. That failed too — :class:UnsupportedMeshFormatError, naming what is installed.

Parameters:

Name Type Description Default
path str | Path

Path to the file. A GDAL virtual-filesystem path (/vsimem/, /vsizip/, /vsicurl/, …) is passed straight to GDAL rather than checked on disk.

required
mesh_name str | None

Which topology to read, for a file declaring more than one (see :meth:mesh_names). None (the default) takes the first.

None
driver str | None

Name of a registered mesh driver to use, bypassing detection — the name a plugin declares, not a GDAL driver short name. None (the default) resolves as described above.

None
lazy bool

Defer reading variable values until first access. Forwarded to the driver, which honours it when it declares lazy_data. The built-in UGRID reader is always lazy, so it rejects lazy=False rather than ignoring it.

True

Returns:

Type Description
UgridDataset

UgridDataset instance.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

DriverNotExistError

If driver names a driver that is not installed.

UnsupportedMeshFormatError

If no installed driver reads the file, and the built-in UGRID reader cannot either.

IsADirectoryError

The path is a directory that no driver claims.

TypeError

lazy=False was asked of the built-in UGRID reader, which is always lazy and so cannot honour it.

RuntimeError

GDAL cannot open a file that reached the built-in reader by its own suffix. A file whose suffix no driver claimed is reported as :class:UnsupportedMeshFormatError instead, so this is now the native route only.

ValueError

If no UGRID topology is found in the file, or mesh_name names a topology the file does not declare.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def read_file(
    cls,
    path: str | Path,
    mesh_name: str | None = None,
    driver: str | None = None,
    lazy: bool = True,
) -> UgridDataset:
    """Open a mesh file.

    UGRID NetCDF is read here. Any other format — 2DM, Selafin, DFSU, XMDF, … — is read by a
    third-party driver registered into the ``pyramids.mesh_drivers`` entry-point group. A
    non-NetCDF suffix is dispatched by detection; a NetCDF suffix is read by the built-in
    reader first, and only a file that opens but carries no UGRID topology falls back to a
    driver claiming that suffix. Either way a successful UGRID read triggers no driver
    discovery, so a ``.nc`` read still pays nothing.

    Resolution order:

    1. ``driver`` given — that driver, or an error. Never falls back.
    2. A ``/vsi`` path or a NetCDF suffix — the built-in UGRID reader. If a NetCDF-suffixed
       file opens but declares no UGRID topology, a registered driver claiming that suffix
       is tried before giving up, so 3Di, TUFLOW FV and other NetCDF-based formats are
       reachable; discovery runs only after the built-in read has already failed.
    3. Otherwise a registered driver claiming the suffix whose ``can_open`` accepts the file.
    4. Nothing claimed it — the built-in reader anyway, so a NetCDF file under an unusual
       suffix still opens exactly as it always did.
    5. That failed too — :class:`UnsupportedMeshFormatError`, naming what is installed.

    Args:
        path: Path to the file. A GDAL virtual-filesystem path
            (``/vsimem/``, ``/vsizip/``, ``/vsicurl/``, …) is passed straight to GDAL
            rather than checked on disk.
        mesh_name: Which topology to read, for a file declaring more than one (see
            :meth:`mesh_names`). ``None`` (the default) takes the first.
        driver: Name of a registered **mesh** driver to use, bypassing detection — the
            name a plugin declares, not a GDAL driver short name. ``None`` (the default)
            resolves as described above.
        lazy: Defer reading variable values until first access. Forwarded to the driver,
            which honours it when it declares ``lazy_data``. The built-in UGRID reader is
            always lazy, so it rejects ``lazy=False`` rather than ignoring it.

    Returns:
        UgridDataset instance.

    Raises:
        FileNotFoundError: If the file does not exist.
        DriverNotExistError: If ``driver`` names a driver that is not installed.
        UnsupportedMeshFormatError: If no installed driver reads the file, and the
            built-in UGRID reader cannot either.
        IsADirectoryError: The path is a directory that no driver claims.
        TypeError: ``lazy=False`` was asked of the built-in UGRID reader, which is always
            lazy and so cannot honour it.
        RuntimeError: GDAL cannot open a file that reached the built-in reader by its
            own suffix. A file whose suffix no driver claimed is reported as
            :class:`UnsupportedMeshFormatError` instead, so this is now the native
            route only.
        ValueError: If no UGRID topology is found in the file, or ``mesh_name`` names
            a topology the file does not declare.
    """
    selected, native = _resolve_read_driver(path, driver)
    if selected is not None:
        result = _read_through_driver(selected, path, mesh_name, cls, lazy)
    else:
        try:
            result = cls._read_ugrid_netcdf(
                path, mesh_name, wrap_unreadable=not native, lazy=lazy
            )
        except NoMeshTopologyError:
            # A NetCDF file that opened but carries no UGRID topology -- a 3Di or
            # TUFLOW FV result. Only now, after the built-in read has failed, consult a
            # driver claiming the suffix; if none does, the original error stands. `lazy`
            # is forwarded to the driver, which may honour an eager read even though the
            # built-in reader cannot. A genuine UGRID file with `lazy=False` raised
            # TypeError inside `_read_ugrid_netcdf` instead, before reading any geometry.
            fallback = _netcdf_fallback_driver(path, driver)
            if fallback is None:
                raise
            result = _read_through_driver(fallback, path, mesh_name, cls, lazy)
    return result

set_crs(crs=None, epsg=None) #

Assign a CRS to a mesh that has none — no reprojection.

Exactly one of crs or epsg must be given. The CRS is written in place to the dataset and the underlying :class:Mesh2d, so :attr:epsg, :attr:crs_wkt, and :attr:crs all reflect the new value immediately.

This is the complement of :meth:to_crs, which reprojects coordinates. set_crs only declares the coordinate system the existing coordinates are already in.

Parameters:

Name Type Description Default
crs str | None

WKT string describing the CRS.

None
epsg int | None

EPSG code (e.g. 4326).

None

Raises:

Type Description
ValueError

If neither crs nor epsg is provided, or if both are provided.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def set_crs(self, crs: str | None = None, epsg: int | None = None) -> None:
    """Assign a CRS to a mesh that has none — no reprojection.

    Exactly one of *crs* or *epsg* must be given. The CRS is written
    in place to the dataset **and** the underlying :class:`Mesh2d`,
    so :attr:`epsg`, :attr:`crs_wkt`, and :attr:`crs` all reflect
    the new value immediately.

    This is the complement of :meth:`to_crs`, which *reprojects*
    coordinates. ``set_crs`` only declares the coordinate system the
    existing coordinates are already in.

    Args:
        crs: WKT string describing the CRS.
        epsg: EPSG code (e.g. ``4326``).

    Raises:
        ValueError: If neither *crs* nor *epsg* is provided, or if
            both are provided.
    """
    wkt, crs_obj = resolve_crs(self._mesh, crs=crs, epsg=epsg)
    self._crs_wkt = wkt
    self._cached_crs = crs_obj

equals(other) #

Value equality — same mesh, same variable values at non-missing positions.

Compares node coordinates, face connectivity, CRS (by EPSG), variable names, and per-variable values (ignoring positions where either side is nodata/NaN).

Parameters:

Name Type Description Default
other object

The object to compare against. Returns False immediately if other is not a UgridDataset.

required

Returns:

Type Description
bool

True when the two datasets are value-equal.

See Also

identical: Strict comparison that also checks dtype, nodata sentinels, CRS WKT, and global attributes.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def equals(self, other: object) -> bool:
    """Value equality — same mesh, same variable values at non-missing positions.

    Compares node coordinates, face connectivity, CRS (by EPSG),
    variable names, and per-variable values (ignoring positions
    where either side is nodata/NaN).

    Args:
        other: The object to compare against.  Returns ``False``
            immediately if *other* is not a ``UgridDataset``.

    Returns:
        ``True`` when the two datasets are value-equal.

    See Also:
        identical: Strict comparison that also checks dtype,
            nodata sentinels, CRS WKT, and global attributes.
    """
    if not isinstance(other, UgridDataset):
        return False
    result = self._mesh_equals(other)
    if result:
        result = self.epsg == other.epsg
    if result:
        result = set(self._data_variables) == set(other._data_variables)
    if result:
        result = self._vars_value_equal(self._data_variables, other._data_variables)
    return result

identical(other) #

Strict equality — same dtype, same values, same nodata, same attributes.

Everything must match exactly, including NaN positions, dtypes, nodata sentinels, CRS WKT, and global attributes.

Parameters:

Name Type Description Default
other object

The object to compare against. Returns False immediately if other is not a UgridDataset.

required

Returns:

Type Description
bool

True when the two datasets are bitwise-identical.

See Also

equals: Looser comparison that ignores nodata positions, dtype differences, and attribute mismatches.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def identical(self, other: object) -> bool:
    """Strict equality — same dtype, same values, same nodata, same attributes.

    Everything must match exactly, including NaN positions, dtypes,
    nodata sentinels, CRS WKT, and global attributes.

    Args:
        other: The object to compare against.  Returns ``False``
            immediately if *other* is not a ``UgridDataset``.

    Returns:
        ``True`` when the two datasets are bitwise-identical.

    See Also:
        equals: Looser comparison that ignores nodata positions,
            dtype differences, and attribute mismatches.
    """
    if not isinstance(other, UgridDataset):
        return False
    result = self._mesh_equals(other)
    if result:
        result = self._crs_identical(other)
    if result:
        result = self._global_attributes == other._global_attributes
    if result:
        result = set(self._data_variables) == set(other._data_variables)
    if result:
        result = self._vars_identical(self._data_variables, other._data_variables)
    return result

get_data(variable_name) #

Get a data variable by name.

Parameters:

Name Type Description Default
variable_name str

Name of the data variable.

required

Returns:

Type Description
MeshVariable

MeshVariable instance.

Raises:

Type Description
KeyError

If the variable name is not found.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def get_data(self, variable_name: str) -> MeshVariable:
    """Get a data variable by name.

    Args:
        variable_name: Name of the data variable.

    Returns:
        MeshVariable instance.

    Raises:
        KeyError: If the variable name is not found.
    """
    if variable_name not in self._data_variables:
        raise KeyError(
            f"Variable '{variable_name}' not found. "
            f"Available: {self.data_variable_names}"
        )
    result = self._data_variables[variable_name]
    return result

__getitem__(key) #

Get a data variable by name using bracket notation.

Parameters:

Name Type Description Default
key str

The variable name.

required

Returns:

Name Type Description
MeshVariable MeshVariable

The variable.

Raises:

Type Description
KeyError

No variable is named key; the message lists the available names.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def __getitem__(self, key: str) -> MeshVariable:
    """Get a data variable by name using bracket notation.

    Args:
        key: The variable name.

    Returns:
        MeshVariable: The variable.

    Raises:
        KeyError: No variable is named ``key``; the message lists the available names.
    """
    return self.get_data(key)

__contains__(key) #

Whether key names a data variable of this dataset.

Parameters:

Name Type Description Default
key str

The variable name to test.

required

Returns:

Name Type Description
bool bool

True when the dataset carries a variable of that name.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def __contains__(self, key: str) -> bool:
    """Whether ``key`` names a data variable of this dataset.

    Args:
        key: The variable name to test.

    Returns:
        bool: True when the dataset carries a variable of that name.
    """
    return key in self._data_variables

__len__() #

The number of data variables.

Returns:

Name Type Description
int int

How many data variables the dataset carries. Note this counts variables,

int

not elements -- :attr:n_face / :attr:n_node / :attr:n_edge are the mesh

int

sizes.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def __len__(self) -> int:
    """The number of data variables.

    Returns:
        int: How many data variables the dataset carries. Note this counts *variables*,
        not elements -- :attr:`n_face` / :attr:`n_node` / :attr:`n_edge` are the mesh
        sizes.
    """
    return len(self._data_variables)

__iter__() #

Iterate over the data variable names.

Returns:

Type Description
Any

Iterator[str]: The variable names, in insertion order -- so list(dataset)

Any

and dataset.keys() agree, and for name in dataset reads like a mapping.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def __iter__(self) -> Any:
    """Iterate over the data variable names.

    Returns:
        Iterator[str]: The variable names, in insertion order -- so ``list(dataset)``
        and ``dataset.keys()`` agree, and ``for name in dataset`` reads like a mapping.
    """
    return iter(self._data_variables)

keys() #

The data variable names (read-only mapping surface).

Returns:

Type Description
list[str]

list[str]: The names, in insertion order. A list rather than a view, so it does

list[str]

not track later edits -- every variable edit returns a new dataset anyway.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def keys(self) -> list[str]:
    """The data variable names (read-only mapping surface).

    Returns:
        list[str]: The names, in insertion order. A list rather than a view, so it does
        not track later edits -- every variable edit returns a new dataset anyway.
    """
    return list(self._data_variables.keys())

values() #

The data variables (read-only mapping surface).

Returns:

Type Description
list[MeshVariable]

list[MeshVariable]: The variables, in the same order as :meth:keys. The

list[MeshVariable]

variables themselves are not copied, so reading .data on one still fires its

list[MeshVariable]

lazy loader.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def values(self) -> list[MeshVariable]:
    """The data variables (read-only mapping surface).

    Returns:
        list[MeshVariable]: The variables, in the same order as :meth:`keys`. The
        variables themselves are not copied, so reading ``.data`` on one still fires its
        lazy loader.
    """
    return list(self._data_variables.values())

items() #

The (name, variable) pairs (read-only mapping surface).

Returns:

Type Description
list[tuple[str, MeshVariable]]

list[tuple[str, MeshVariable]]: One pair per variable, in insertion order.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def items(self) -> list[tuple[str, MeshVariable]]:
    """The ``(name, variable)`` pairs (read-only mapping surface).

    Returns:
        list[tuple[str, MeshVariable]]: One pair per variable, in insertion order.
    """
    return list(self._data_variables.items())

get(key, default=None) #

The variable key, or default when it is absent.

Parameters:

Name Type Description Default
key str

The variable name to look up.

required
default Any

What to answer when no variable is named key. Defaults to None.

None

Returns:

Type Description
MeshVariable | Any

MeshVariable | Any: The variable, or default.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def get(self, key: str, default: Any = None) -> MeshVariable | Any:
    """The variable ``key``, or ``default`` when it is absent.

    Args:
        key: The variable name to look up.
        default: What to answer when no variable is named ``key``. Defaults to ``None``.

    Returns:
        MeshVariable | Any: The variable, or ``default``.
    """
    return self._data_variables.get(key, default)

with_variable(name, data, *, location='face', nodata=None) #

Return a new dataset with name added or replaced.

UGRID derivations are immutable — unlike NetCDF.set_variable this does not mutate in place but returns a fresh dataset. A 2-D data array is treated as temporal (leading axis = time); a 1-D array is a static per-element variable.

Parameters:

Name Type Description Default
name str

Variable name to add or replace.

required
data ndarray

The values; (n_elements,) static or (n_time, n_elements) temporal.

required
location str

Mesh location — "face", "node" or "edge". Defaults to "face".

'face'
nodata float | None

Optional no-data value for the new variable.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset carrying the variable.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def with_variable(
    self,
    name: str,
    data: np.ndarray,
    *,
    location: str = "face",
    nodata: float | None = None,
) -> UgridDataset:
    """Return a new dataset with ``name`` added or replaced.

    UGRID derivations are immutable — unlike ``NetCDF.set_variable`` this does not mutate
    in place but returns a fresh dataset. A 2-D ``data`` array is treated as temporal
    (leading axis = time); a 1-D array is a static per-element variable.

    Args:
        name: Variable name to add or replace.
        data: The values; ``(n_elements,)`` static or ``(n_time, n_elements)`` temporal.
        location: Mesh location — ``"face"``, ``"node"`` or ``"edge"``. Defaults to
            ``"face"``.
        nodata: Optional no-data value for the new variable.

    Returns:
        UgridDataset: A new dataset carrying the variable.
    """
    arr = np.asarray(data)
    variable = MeshVariable(
        name=name,
        location=location,
        mesh_name=self.mesh_name,
        shape=arr.shape,
        nodata=nodata,
        _data=arr,
    )
    new_vars = dict(self._data_variables)
    new_vars[name] = variable
    return self._rebuild(new_vars)

drop_variables(names) #

Return a new dataset without the named variable(s).

Parameters:

Name Type Description Default
names str | list[str]

A variable name, or a list of them, to drop.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset without those variables.

Raises:

Type Description
KeyError

A named variable is not present.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def drop_variables(self, names: str | list[str]) -> UgridDataset:
    """Return a new dataset without the named variable(s).

    Args:
        names: A variable name, or a list of them, to drop.

    Returns:
        UgridDataset: A new dataset without those variables.

    Raises:
        KeyError: A named variable is not present.
    """
    drop = [names] if isinstance(names, str) else list(names)
    new_vars = dict(self._data_variables)
    for name in drop:
        if name not in new_vars:
            raise KeyError(
                f"Variable {name!r} not found. Available: {self.data_variable_names}"
            )
        del new_vars[name]
    return self._rebuild(new_vars)

rename_variable(old, new) #

Return a new dataset with variable old renamed to new.

Parameters:

Name Type Description Default
old str

The current variable name.

required
new str

The new name.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with the variable renamed.

Raises:

Type Description
KeyError

old is not present.

ValueError

new already names a different variable.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def rename_variable(self, old: str, new: str) -> UgridDataset:
    """Return a new dataset with variable ``old`` renamed to ``new``.

    Args:
        old: The current variable name.
        new: The new name.

    Returns:
        UgridDataset: A new dataset with the variable renamed.

    Raises:
        KeyError: ``old`` is not present.
        ValueError: ``new`` already names a different variable.
    """
    if old not in self._data_variables:
        raise KeyError(
            f"Variable {old!r} not found. Available: {self.data_variable_names}"
        )
    if new in self._data_variables and new != old:
        raise ValueError(f"Variable {new!r} already exists.")
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if name == old:
            # `replace` keeps the lazy loader and every other field, only re-labelling
            # the variable, so a rename never forces a read.
            new_vars[new] = replace(var, name=new)
        else:
            new_vars[name] = var
    return self._rebuild(new_vars)

to_dataset(variable_name, cell_size, method='nearest', bounds=None, epsg=None, nodata=-9999.0) #

Convert a mesh variable to a regular-grid Dataset.

Interpolates mesh data onto a regular grid and returns a standard pyramids Dataset. This is the bridge between unstructured (UGRID) and structured (raster) worlds.

Parameters:

Name Type Description Default
variable_name str

Name of the data variable to rasterize.

required
cell_size float

Target grid cell size in coordinate units.

required
method str

Interpolation method ("nearest" or "linear").

'nearest'
bounds tuple[float, float, float, float] | None

Target (xmin, ymin, xmax, ymax). Defaults to mesh bounds.

None
epsg int | None

Target EPSG code. Defaults to mesh CRS.

None
nodata float

No-data value for the output raster.

-9999.0

Returns:

Type Description
Dataset

pyramids Dataset with the interpolated data.

Raises:

Type Description
KeyError

No variable is named variable_name.

ValueError

The variable exists but holds no data (nothing was loaded and it carries no lazy loader), so there is nothing to interpolate.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_dataset(
    self,
    variable_name: str,
    cell_size: float,
    method: str = "nearest",
    bounds: tuple[float, float, float, float] | None = None,
    epsg: int | None = None,
    nodata: float = -9999.0,
) -> Dataset:
    """Convert a mesh variable to a regular-grid Dataset.

    Interpolates mesh data onto a regular grid and returns a
    standard pyramids Dataset. This is the bridge between
    unstructured (UGRID) and structured (raster) worlds.

    Args:
        variable_name: Name of the data variable to rasterize.
        cell_size: Target grid cell size in coordinate units.
        method: Interpolation method ("nearest" or "linear").
        bounds: Target (xmin, ymin, xmax, ymax). Defaults to mesh bounds.
        epsg: Target EPSG code. Defaults to mesh CRS.
        nodata: No-data value for the output raster.

    Returns:
        pyramids Dataset with the interpolated data.

    Raises:
        KeyError: No variable is named ``variable_name``.
        ValueError: The variable exists but holds no data (nothing was loaded and it
            carries no lazy loader), so there is nothing to interpolate.
    """
    var = self.get_data(variable_name)
    data = var.data
    if data is None:
        raise ValueError(f"Variable '{variable_name}' has no data loaded.")
    if var.has_time:
        # First step along the variable's own time axis (not blindly axis 0, which for
        # a trailing-time variable would take the first face) — see `_element_values`.
        data = np.take(np.asarray(data), 0, axis=cast("int", var.time_index))

    grid_array, geotransform = mesh_to_grid(
        mesh=self._mesh,
        data=data,
        location=var.location,
        cell_size=cell_size,
        method=method,
        bounds=bounds,
        nodata=nodata,
    )

    # `crs_spec` rather than `self.epsg or 4326`: a mesh carrying a projected
    # WKT with no EPSG code has `epsg is None`, and the old default stamped
    # EPSG:4326 onto metre coordinates. That is the case this resolves.
    #
    # The `or 4326` behind it keeps the *other* case as it was. A mesh with
    # no CRS at all -- no code and no WKT -- has always rasterised to WGS 84
    # here, and `to_dataset(...).to_file("out.tif")` writing a GeoTIFF with
    # no CRS instead would be a silent behaviour change for every caller
    # holding such a mesh. Narrowing that default is a decision for its own
    # change, not a side effect of teaching this line about WKT.
    target_epsg = (
        epsg if epsg is not None else crs_spec(self.epsg, self.crs_wkt) or 4326
    )
    result = Dataset.from_array(
        grid_array,
        no_data_value=nodata,
        geo_ref=GeoReference(
            geo=cast(
                "tuple[float, float, float, float, float, float]", geotransform
            ),
            epsg=target_epsg,
        ),
    )
    return result

crop(mask=None, touch=True, *, bbox=None, epsg=None) #

Crop the mesh to a polygon mask or a bbox — the unstructured-mesh analogue of crop.

The mesh equivalent of :meth:pyramids.dataset.Dataset.crop / :meth:NetCDF.crop. Rather than warping a raster, it selects the faces that fall inside the region (renumbering the node connectivity for the resulting sub-mesh) and keeps the data on the surviving elements. Delegates to :meth:clip for a polygon and :meth:subset_by_bounds for a bbox; this method exists so the spatial-subset call is named crop across the raster and mesh classes alike.

Parameters:

Name Type Description Default
mask Any

Polygon mask — a shapely geometry, GeoDataFrame, or FeatureCollection. Mutually exclusive with bbox.

None
touch bool

Applies only to a polygon mask: if True (default), keep faces that touch the mask boundary; if False, keep only faces fully inside it. Ignored for bbox, which always selects faces by its axis-aligned envelope (subset_by_bounds). Defaults to True.

True
bbox tuple or list of 4 floats, keyword-only

(west, south, east, north) in the mesh CRS, or in epsg when supplied. Accepts a tuple or a list. Selects faces by the axis-aligned envelope; not affected by touch. Mutually exclusive with mask.

None
epsg (int, keyword - only)

CRS of bbox. When it differs from the mesh CRS the box is reprojected to the mesh CRS and subset by its envelope; when it equals the mesh CRS it is a no-op. Defaults to the mesh CRS.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new sub-mesh — faces inside the region, connectivity renumbered, and data variables subset to the surviving elements.

Raises:

Type Description
ValueError

If both mask and bbox are supplied, if bbox is not a 4-tuple, or if epsg is given for a bbox but the mesh has no CRS to reproject into.

TypeError

If neither mask nor bbox is supplied.

Examples:

  • Crop a mesh to a polygon (faces intersecting it survive):
    >>> from shapely.geometry import Polygon
    >>> from pyramids.netcdf import UgridDataset
    >>> ug = UgridDataset.read_file("mesh.nc")                        # doctest: +SKIP
    >>> sub = ug.crop(Polygon([(-1, -1), (0, -1), (0, 1), (-1, 1)]))  # doctest: +SKIP
    >>> sub.n_face <= ug.n_face                                       # doctest: +SKIP
    True
    
  • Crop to a bounding box in the mesh's own CRS:
    >>> sub = ug.crop(bbox=(-1.0, -1.0, 0.0, 1.0))                    # doctest: +SKIP
    
See Also

clip: Polygon-mask subsetting that crop delegates to when mask is given. subset_by_bounds: Bounding-box subsetting that crop delegates to when bbox is given. pyramids.dataset.Dataset.crop: The raster equivalent on a gridded dataset.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def crop(
    self,
    mask: Any = None,
    touch: bool = True,
    *,
    bbox: tuple[float, float, float, float] | list[float] | None = None,
    epsg: int | None = None,
) -> UgridDataset:
    """Crop the mesh to a polygon mask or a bbox — the unstructured-mesh analogue of crop.

    The mesh equivalent of :meth:`pyramids.dataset.Dataset.crop` / :meth:`NetCDF.crop`. Rather
    than warping a raster, it selects the **faces** that fall inside the region (renumbering the
    node connectivity for the resulting sub-mesh) and keeps the data on the surviving elements.
    Delegates to :meth:`clip` for a polygon and :meth:`subset_by_bounds` for a bbox; this method
    exists so the spatial-subset call is named ``crop`` across the raster and mesh classes alike.

    Args:
        mask (Any):
            Polygon mask — a shapely geometry, ``GeoDataFrame``, or ``FeatureCollection``.
            Mutually exclusive with ``bbox``.
        touch (bool):
            Applies only to a polygon ``mask``: if ``True`` (default), keep faces that touch the
            mask boundary; if ``False``, keep only faces fully inside it. Ignored for ``bbox``,
            which always selects faces by its axis-aligned envelope (``subset_by_bounds``).
            Defaults to True.
        bbox (tuple or list of 4 floats, keyword-only):
            ``(west, south, east, north)`` in the mesh CRS, or in ``epsg`` when supplied. Accepts
            a tuple or a list. Selects faces by the axis-aligned envelope; not affected by
            ``touch``. Mutually exclusive with ``mask``.
        epsg (int, keyword-only):
            CRS of ``bbox``. When it differs from the mesh CRS the box is reprojected to the mesh
            CRS and subset by its envelope; when it equals the mesh CRS it is a no-op. Defaults to
            the mesh CRS.

    Returns:
        UgridDataset: A new sub-mesh — faces inside the region, connectivity renumbered, and data
            variables subset to the surviving elements.

    Raises:
        ValueError: If both ``mask`` and ``bbox`` are supplied, if ``bbox`` is not a 4-tuple, or
            if ``epsg`` is given for a ``bbox`` but the mesh has no CRS to reproject into.
        TypeError: If neither ``mask`` nor ``bbox`` is supplied.

    Examples:
        - Crop a mesh to a polygon (faces intersecting it survive):
            ```python
            >>> from shapely.geometry import Polygon
            >>> from pyramids.netcdf import UgridDataset
            >>> ug = UgridDataset.read_file("mesh.nc")                        # doctest: +SKIP
            >>> sub = ug.crop(Polygon([(-1, -1), (0, -1), (0, 1), (-1, 1)]))  # doctest: +SKIP
            >>> sub.n_face <= ug.n_face                                       # doctest: +SKIP
            True

            ```
        - Crop to a bounding box in the mesh's own CRS:
            ```python
            >>> sub = ug.crop(bbox=(-1.0, -1.0, 0.0, 1.0))                    # doctest: +SKIP

            ```

    See Also:
        clip: Polygon-mask subsetting that ``crop`` delegates to when ``mask`` is given.
        subset_by_bounds: Bounding-box subsetting that ``crop`` delegates to when ``bbox`` is
            given.
        pyramids.dataset.Dataset.crop: The raster equivalent on a gridded dataset.
    """
    if bbox is not None:
        if mask is not None:
            raise ValueError("crop accepts either `mask` or `bbox`, not both")
        if len(bbox) != 4:
            raise ValueError(
                "bbox must be a 4-tuple of (west, south, east, north), "
                f"got {len(bbox)} value(s)"
            )
        west, south, east, north = bbox
        if epsg is not None and (self.epsg is None or int(epsg) != int(self.epsg)):
            if self.epsg is None:
                raise ValueError(
                    f"cannot reproject a bbox given in EPSG:{int(epsg)} into a mesh that has no "
                    "CRS; drop epsg to treat the bbox as native coordinates"
                )
            # Reproject the bbox to the mesh CRS and subset by its envelope, so the bbox path
            # selects faces with the same rule (subset_by_bounds) regardless of the source CRS.
            west, south, east, north = (
                gpd.GeoSeries([box(west, south, east, north)], crs=epsg)
                .to_crs(self.epsg)
                .total_bounds
            )
        result = self.subset_by_bounds(west, south, east, north)
    elif mask is not None:
        result = self.clip(mask, touch=touch)
    else:
        raise TypeError(
            "crop requires a `mask` (polygon) or a `bbox` (west, south, east, north) tuple"
        )
    return result

clip(mask, touch=True) #

Clip the mesh to a polygon mask.

Selects faces that intersect (touch=True) or are fully contained within (touch=False) the mask polygon.

Parameters:

Name Type Description Default
mask Any

Polygon mask (GeoDataFrame, FeatureCollection, or Shapely geometry).

required
touch bool

If True, include faces touching the boundary.

True

Returns:

Type Description
UgridDataset

New UgridDataset with clipped mesh and data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def clip(self, mask: Any, touch: bool = True) -> UgridDataset:
    """Clip the mesh to a polygon mask.

    Selects faces that intersect (touch=True) or are fully
    contained within (touch=False) the mask polygon.

    Args:
        mask: Polygon mask (GeoDataFrame, FeatureCollection,
            or Shapely geometry).
        touch: If True, include faces touching the boundary.

    Returns:
        New UgridDataset with clipped mesh and data.
    """
    mesh, data_variables = clip_mesh(self, mask, touch=touch)
    return self._wrap_subset(mesh, data_variables)

subset_by_bounds(xmin, ymin, xmax, ymax) #

Subset mesh to faces within a bounding box.

Parameters:

Name Type Description Default
xmin float

Minimum x-coordinate.

required
ymin float

Minimum y-coordinate.

required
xmax float

Maximum x-coordinate.

required
ymax float

Maximum y-coordinate.

required

Returns:

Type Description
UgridDataset

New UgridDataset with subset mesh and data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def subset_by_bounds(
    self,
    xmin: float,
    ymin: float,
    xmax: float,
    ymax: float,
) -> UgridDataset:
    """Subset mesh to faces within a bounding box.

    Args:
        xmin: Minimum x-coordinate.
        ymin: Minimum y-coordinate.
        xmax: Maximum x-coordinate.
        ymax: Maximum y-coordinate.

    Returns:
        New UgridDataset with subset mesh and data.
    """
    mesh, data_variables = subset_by_bounds(self, xmin, ymin, xmax, ymax)
    return self._wrap_subset(mesh, data_variables)

to_crs(to_epsg) #

Reproject all node coordinates to a new CRS.

Uses pyproj.Transformer to reproject node coordinates. Face/edge center coordinates are recomputed after reprojection. Data values are preserved — only coordinates change.

Parameters:

Name Type Description Default
to_epsg int

Target EPSG code.

required

Returns:

Type Description
UgridDataset

New UgridDataset with reprojected coordinates.

Raises:

Type Description
ValueError

The mesh declares neither an EPSG code nor a WKT, so there is no source CRS to reproject from.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_crs(self, to_epsg: int) -> UgridDataset:
    """Reproject all node coordinates to a new CRS.

    Uses pyproj.Transformer to reproject node coordinates.
    Face/edge center coordinates are recomputed after reprojection.
    Data values are preserved — only coordinates change.

    Args:
        to_epsg: Target EPSG code.

    Returns:
        New UgridDataset with reprojected coordinates.

    Raises:
        ValueError: The mesh declares neither an EPSG code nor a WKT, so there is no
            source CRS to reproject from.
    """
    # The mesh may describe its CRS by WKT alone, with no EPSG code to
    # resolve; `crs_spec` returns whichever of the two is usable, so a
    # projected mesh stops being refused for a CRS it plainly has.
    source_crs = crs_spec(self.epsg, self.crs_wkt)
    if source_crs is None:
        raise ValueError(
            "Cannot reproject: source CRS is unknown. "
            "Set CRS before calling to_crs()."
        )

    # Through `crs_from_user_input` so a mesh in a CRS whose code only GDAL's
    # PROJ database carries still reprojects (issue #943). The source goes in
    # as-is rather than as `EPSG:{...}`: `crs_spec` yields the mesh's WKT when
    # there is no usable code, and prefixing that builds the nonsense
    # `EPSG:PROJCS[...]`. The target is always a bare integer code.
    transformer = Transformer.from_crs(
        crs_from_user_input(source_crs),
        crs_from_user_input(f"EPSG:{to_epsg}"),
        always_xy=True,
    )
    new_node_x, new_node_y = transformer.transform(
        self._mesh.node_x,
        self._mesh.node_y,
    )

    new_face_x = None
    new_face_y = None
    if self._mesh.has_face_coords:
        new_face_x, new_face_y = transformer.transform(
            self._mesh.face_x,
            self._mesh.face_y,
        )

    new_edge_x = None
    new_edge_y = None
    if self._mesh.has_edge_coords:
        new_edge_x, new_edge_y = transformer.transform(
            self._mesh.edge_x,
            self._mesh.edge_y,
        )

    new_mesh = Mesh2d(
        node_x=new_node_x,
        node_y=new_node_y,
        face_node_connectivity=self._mesh.face_node_connectivity,
        edge_node_connectivity=self._mesh.edge_node_connectivity,
        face_edge_connectivity=self._mesh.face_edge_connectivity,
        face_face_connectivity=self._mesh.face_face_connectivity,
        edge_face_connectivity=self._mesh.edge_face_connectivity,
        face_x=new_face_x,
        face_y=new_face_y,
        edge_x=new_edge_x,
        edge_y=new_edge_y,
    )

    srs = sr_from_epsg(to_epsg)
    new_crs_wkt = srs.ExportToWkt()

    new_topo_info = None
    if self._topology_info is not None:
        new_topo_info = replace(self._topology_info, crs_wkt=new_crs_wkt)

    # `type(self)` and `file_name`, as every other derivation does: hard-coding
    # `UgridDataset(` silently downgraded a subclass, and dropping `file_name` made the
    # attribute unreliable rather than absent.
    result = type(self)(
        mesh=new_mesh,
        data_variables=self._data_variables,
        global_attributes=self._global_attributes,
        topology_info=new_topo_info,
        crs_wkt=new_crs_wkt,
        file_name=self._file_name,
        volume_topology=self._volume_topology,
    )
    return result

sel_time(index) #

Select a single time step from all temporal variables.

Non-temporal variables are kept unchanged.

Parameters:

Name Type Description Default
index int

Time step index.

required

Returns:

Type Description
UgridDataset

New UgridDataset with single time step data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sel_time(self, index: int) -> UgridDataset:
    """Select a single time step from all temporal variables.

    Non-temporal variables are kept unchanged.

    Args:
        index: Time step index.

    Returns:
        New UgridDataset with single time step data.
    """
    new_data_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if var.has_time:
            new_data_vars[name] = var.with_data(
                var.sel_time(index), active=var._time_sliced_active(index, None)
            )
        else:
            new_data_vars[name] = var

    # See `to_crs`: `type(self)` keeps a subclass, and `file_name` is carried.
    result = type(self)(
        mesh=self._mesh,
        data_variables=new_data_vars,
        global_attributes=self._global_attributes,
        topology_info=self._topology_info,
        crs_wkt=self._crs_wkt,
        file_name=self._file_name,
        volume_topology=self._volume_topology,
    )
    return result

sel_time_range(start, stop) #

Select a time range from all temporal variables.

Parameters:

Name Type Description Default
start int

Start index (inclusive).

required
stop int

Stop index (exclusive).

required

Returns:

Type Description
UgridDataset

New UgridDataset with the selected time range.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sel_time_range(self, start: int, stop: int) -> UgridDataset:
    """Select a time range from all temporal variables.

    Args:
        start: Start index (inclusive).
        stop: Stop index (exclusive).

    Returns:
        New UgridDataset with the selected time range.
    """
    new_data_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if var.has_time:
            new_data_vars[name] = var.sel_time_range(start, stop)
        else:
            new_data_vars[name] = var

    # See `to_crs`: `type(self)` keeps a subclass, and `file_name` is carried.
    result = type(self)(
        mesh=self._mesh,
        data_variables=new_data_vars,
        global_attributes=self._global_attributes,
        topology_info=self._topology_info,
        crs_wkt=self._crs_wkt,
        file_name=self._file_name,
        volume_topology=self._volume_topology,
    )
    return result

attach_data(path, driver=None, lazy=True) #

Attach a results-only file's variables to this mesh.

Some formats carry values but no topology — an SMS .dat, an XMDF, an XDMF — and must be paired with a mesh read from elsewhere. Those drivers declare needs_mesh, and :meth:read_file refuses them, pointing here.

>>> mesh = UgridDataset.read_file("domain.2dm")       # doctest: +SKIP
>>> result = mesh.attach_data("velocity.dat")         # doctest: +SKIP

The driver returns only the variables it read; this method merges them onto the dataset. That division is deliberate — it makes a name the dataset already defines an unambiguous collision, and means a driver cannot drop the dataset's own variables by rebuilding the mapping.

The driver checks the file's declared element count against this mesh. That check is the only safeguard there is: a bare results file carries nothing identifying the mesh it belongs to, so attaching it to the wrong one would otherwise produce a plausible and entirely wrong dataset.

Parameters:

Name Type Description Default
path str | Path

The results file to read.

required
driver str | None

Name of a registered driver to use, bypassing detection. None (the default) picks the needs_mesh driver claiming the file's suffix.

None
lazy bool

Defer reading variable values until first access. Defaults to True.

True

Returns:

Type Description
UgridDataset

A new dataset carrying this mesh plus the attached variables. This dataset is

UgridDataset

unchanged.

Raises:

Type Description
FileNotFoundError

If the results file does not exist.

DriverNotExistError

If driver names a driver that is not installed.

UnsupportedMeshFormatError

If no installed driver can attach this file, the named driver does not declare needs_mesh, or the driver returned something other than a mapping of name to :class:MeshVariable.

ValueError

If the driver returns a variable whose name this dataset already uses, or reports an element-count mismatch against this mesh.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def attach_data(
    self, path: str | Path, driver: str | None = None, lazy: bool = True
) -> UgridDataset:
    """Attach a results-only file's variables to this mesh.

    Some formats carry values but no topology — an SMS ``.dat``, an XMDF, an XDMF — and must
    be paired with a mesh read from elsewhere. Those drivers declare ``needs_mesh``, and
    :meth:`read_file` refuses them, pointing here.

        >>> mesh = UgridDataset.read_file("domain.2dm")       # doctest: +SKIP
        >>> result = mesh.attach_data("velocity.dat")         # doctest: +SKIP

    The driver returns **only the variables it read**; this method merges them onto the
    dataset. That division is deliberate — it makes a name the dataset already defines an
    unambiguous collision, and means a driver cannot drop the dataset's own variables by
    rebuilding the mapping.

    The driver checks the file's declared element count against this mesh. That check is the
    only safeguard there is: a bare results file carries nothing identifying the mesh it
    belongs to, so attaching it to the wrong one would otherwise produce a plausible and
    entirely wrong dataset.

    Args:
        path: The results file to read.
        driver: Name of a registered driver to use, bypassing detection. ``None`` (the
            default) picks the ``needs_mesh`` driver claiming the file's suffix.
        lazy: Defer reading variable values until first access. Defaults to True.

    Returns:
        A new dataset carrying this mesh plus the attached variables. This dataset is
        unchanged.

    Raises:
        FileNotFoundError: If the results file does not exist.
        DriverNotExistError: If ``driver`` names a driver that is not installed.
        UnsupportedMeshFormatError: If no installed driver can attach this file, the
            named driver does not declare ``needs_mesh``, or the driver returned
            something other than a mapping of name to :class:`MeshVariable`.
        ValueError: If the driver returns a variable whose name this dataset already
            uses, or reports an element-count mismatch against this mesh.
    """
    _require_existing_file(path)
    selected = _resolve_attach_driver(path, driver)
    produced = _read_data_through_driver(selected, path, self, lazy)
    collisions = sorted(set(produced) & set(self._data_variables))
    if collisions:
        raise ValueError(
            f"The {selected.name!r} driver read variable(s) {collisions} from "
            f"{str(path)!r}, which this dataset already defines. Rename one side before "
            f"attaching, or drop the existing variable first."
        )
    merged = dict(self._data_variables)
    merged.update(produced)
    return type(self)(
        mesh=self._mesh,
        data_variables=merged,
        global_attributes=self._global_attributes,
        topology_info=self._topology_info,
        crs_wkt=self._crs_wkt,
        volume_topology=self._volume_topology,
        file_name=self._file_name,
    )

to_file(path, driver=None, **options) #

Write the dataset to a file.

Writes UGRID-compliant NetCDF by default: a topology variable, node coordinates, connectivity arrays, face/edge centres, data variables, and global attributes following the UGRID convention.

With driver, writes through a registered third-party driver instead — 2DM, Selafin, PLY and others are writable. The output format is never inferred from the suffix, so to_file("mesh.slf") still writes NetCDF; name the driver to change that.

Parameters:

Name Type Description Default
path str | Path

Output file path.

required
driver str | None

Name of a registered mesh driver to write with, as declared by the plugin providing it (see :func:~pyramids.netcdf.ugrid.mesh_drivers) — not a GDAL driver short name, which is what driver means elsewhere in pyramids. None (the default) writes UGRID NetCDF through the built-in writer, and the output format is never inferred from path's suffix.

None
**options Any

Format-specific settings for the driver, passed through uninterpreted (for example Selafin endianness, or PLY ascii versus binary). The built-in writer takes none, so passing any without a driver raises TypeError rather than dropping them silently.

{}

Raises:

Type Description
DriverNotExistError

If driver names a driver that is not installed.

UnsupportedMeshFormatError

If the named driver cannot write a mesh.

TypeError

If options are given without a driver.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_file(
    self, path: str | Path, driver: str | None = None, **options: Any
) -> None:
    """Write the dataset to a file.

    Writes UGRID-compliant NetCDF by default: a topology variable, node coordinates,
    connectivity arrays, face/edge centres, data variables, and global attributes following
    the UGRID convention.

    With ``driver``, writes through a registered third-party driver instead — 2DM, Selafin,
    PLY and others are writable. The output format is never inferred from the suffix, so
    ``to_file("mesh.slf")`` still writes NetCDF; name the driver to change that.

    Args:
        path: Output file path.
        driver: Name of a registered **mesh** driver to write with, as declared by the
            plugin providing it (see :func:`~pyramids.netcdf.ugrid.mesh_drivers`) — not a
            GDAL driver short name, which is what ``driver`` means elsewhere in pyramids.
            ``None`` (the default) writes UGRID NetCDF through the built-in writer, and
            the output format is never inferred from ``path``'s suffix.
        **options: Format-specific settings for the driver, passed through uninterpreted
            (for example Selafin endianness, or PLY ascii versus binary). The built-in
            writer takes none, so passing any without a ``driver`` raises ``TypeError``
            rather than dropping them silently.

    Raises:
        DriverNotExistError: If ``driver`` names a driver that is not installed.
        UnsupportedMeshFormatError: If the named driver cannot write a mesh.
        TypeError: If ``options`` are given without a ``driver``.
    """
    if driver is not None:
        self._write_through_driver(path, driver, options)
    elif options:
        raise TypeError(
            f"to_file() got unexpected keyword argument(s) "
            f"{sorted(options)}; format options apply to a `driver=` write only."
        )
    else:
        self._write_ugrid_netcdf(Path(path))

to_bytes() #

Serialise the dataset to an in-memory UGRID NetCDF buffer.

Writes through a temporary file because GDAL's NetCDF driver does not support /vsimem/ for multidimensional creation.

Returns:

Name Type Description
bytes bytes

The NetCDF file content, suitable for writing to cloud storage or embedding in a response payload.

See Also

to_file: Write directly to a file on disk. read_file: Class method that reads from a file path or byte buffer.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_bytes(self) -> bytes:
    """Serialise the dataset to an in-memory UGRID NetCDF buffer.

    Writes through a temporary file because GDAL's NetCDF driver
    does not support ``/vsimem/`` for multidimensional creation.

    Returns:
        bytes: The NetCDF file content, suitable for writing to
            cloud storage or embedding in a response payload.

    See Also:
        to_file: Write directly to a file on disk.
        read_file: Class method that reads from a file path or
            byte buffer.
    """
    with tempfile.NamedTemporaryFile(suffix=".nc", delete=False) as tmp:
        tmp_path = Path(tmp.name)
    try:
        self._write_ugrid_netcdf(tmp_path)
        data = tmp_path.read_bytes()
    finally:
        try:
            tmp_path.unlink(missing_ok=True)
        except PermissionError:
            pass
    return data

to_geodataframe(variable_name=None, location='face') #

Convert mesh to a GeoDataFrame.

For faces: each row is a Polygon with data columns. For nodes: each row is a Point. For edges: each row is a LineString.

Parameters:

Name Type Description Default
variable_name str | None

Optional data variable to include as a column.

None
location str

Mesh location ("face", "node", or "edge").

'face'

Returns:

Type Description
GeoDataFrame

geopandas GeoDataFrame.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_geodataframe(
    self,
    variable_name: str | None = None,
    location: str = "face",
) -> gpd.GeoDataFrame:
    """Convert mesh to a GeoDataFrame.

    For faces: each row is a Polygon with data columns.
    For nodes: each row is a Point.
    For edges: each row is a LineString.

    Args:
        variable_name: Optional data variable to include as a column.
        location: Mesh location ("face", "node", or "edge").

    Returns:
        geopandas GeoDataFrame.
    """
    geometries = self._build_geometries(location)

    data_dict: dict[str, Any] = {}
    if variable_name is not None:
        var = self.get_data(variable_name)
        if var.location == location:
            # For a temporal variable only the first step is tabulated; `sel_time(0)` reads just
            # that slab instead of loading every step to slice `[0]` (#982). `has_data_source`
            # avoids a temporal-specific `sel_time` error for a variable with no readable data
            # (checked without forcing a load — review L3).
            if var.has_time:
                var_data = var.sel_time(0) if var.has_data_source else None
            else:
                var_data = var.data
            # A variable with no readable data becomes a length-correct null column rather than
            # raising — pandas rejects a scalar `None` column ("must pass an index") (review L3).
            if var_data is None:
                var_data = np.full(len(geometries), np.nan)
            data_dict[variable_name] = var_data

    gdf = gpd.GeoDataFrame(data_dict, geometry=geometries)
    if self.crs is not None:
        gdf = gdf.set_crs(self.crs)

    result = gdf
    return result

to_feature_collection(variable_name=None, location='face') #

Convert mesh to a pyramids FeatureCollection.

Parameters:

Name Type Description Default
variable_name str | None

Optional data variable to include.

None
location str

Mesh location ("face", "node", or "edge").

'face'

Returns:

Type Description
FeatureCollection

pyramids FeatureCollection.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_feature_collection(
    self,
    variable_name: str | None = None,
    location: str = "face",
) -> FeatureCollection:
    """Convert mesh to a pyramids FeatureCollection.

    Args:
        variable_name: Optional data variable to include.
        location: Mesh location ("face", "node", or "edge").

    Returns:
        pyramids FeatureCollection.
    """
    gdf = self.to_geodataframe(variable_name, location)
    result = FeatureCollection(gdf)
    return result

from_arrays(node_x, node_y, face_node_connectivity, data=None, data_locations=None, epsg=4326, mesh_name=DEFAULT_MESH_NAME) classmethod #

Create a UgridDataset programmatically from arrays.

Plural because an unstructured mesh is not one array: the topology needs node coordinates and a face-node connectivity table before any data can be attached. It therefore takes a flat epsg rather than the :class:~pyramids.base.georeference.GeoReference the gridded constructors take — a mesh carries its own coordinates, so there is no affine transform to describe.

Parameters:

Name Type Description Default
node_x ndarray

Node x-coordinates.

required
node_y ndarray

Node y-coordinates.

required
face_node_connectivity ndarray

(n_faces, max_nodes) array of node indices. Use -1 as fill value for mixed meshes.

required
data dict[str, ndarray] | None

Optional dict mapping variable name to data array.

None
data_locations dict[str, str] | None

Optional dict mapping variable name to location ("face", "node", "edge"). Defaults to "face".

None
epsg int

EPSG code for the CRS.

4326
mesh_name str

Name for the topology variable.

DEFAULT_MESH_NAME

Returns:

Type Description
UgridDataset

UgridDataset instance.

Examples:

  • Build the smallest possible mesh — two triangles — and inspect its topology:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ... )
    >>> (mesh.n_node, mesh.n_face)
    (4, 2)
    >>> mesh.bounds
    (0.0, 0.0, 1.0, 1.0)
    
  • Attach a per-face variable and read it back:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"depth": np.array([1.5, 2.5])},
    ... )
    >>> mesh.data_variable_names
    ['depth']
    >>> mesh["depth"].location
    'face'
    >>> mesh["depth"].data.tolist()
    [1.5, 2.5]
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def from_arrays(
    cls,
    node_x: np.ndarray,
    node_y: np.ndarray,
    face_node_connectivity: np.ndarray,
    data: dict[str, np.ndarray] | None = None,
    data_locations: dict[str, str] | None = None,
    epsg: int = 4326,
    mesh_name: str = DEFAULT_MESH_NAME,
) -> UgridDataset:
    """Create a UgridDataset programmatically from arrays.

    Plural because an unstructured mesh is not one array: the topology
    needs node coordinates *and* a face-node connectivity table before any
    data can be attached. It therefore takes a flat `epsg` rather than the
    :class:`~pyramids.base.georeference.GeoReference` the gridded
    constructors take — a mesh carries its own coordinates, so there is no
    affine transform to describe.

    Args:
        node_x: Node x-coordinates.
        node_y: Node y-coordinates.
        face_node_connectivity: (n_faces, max_nodes) array of node
            indices. Use -1 as fill value for mixed meshes.
        data: Optional dict mapping variable name to data array.
        data_locations: Optional dict mapping variable name to
            location ("face", "node", "edge"). Defaults to "face".
        epsg: EPSG code for the CRS.
        mesh_name: Name for the topology variable.

    Returns:
        UgridDataset instance.

    Examples:
        - Build the smallest possible mesh — two triangles — and inspect
          its topology:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ... )
            >>> (mesh.n_node, mesh.n_face)
            (4, 2)
            >>> mesh.bounds
            (0.0, 0.0, 1.0, 1.0)

            ```
        - Attach a per-face variable and read it back:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"depth": np.array([1.5, 2.5])},
            ... )
            >>> mesh.data_variable_names
            ['depth']
            >>> mesh["depth"].location
            'face'
            >>> mesh["depth"].data.tolist()
            [1.5, 2.5]

            ```
    """
    fnc = Connectivity(
        data=np.asarray(face_node_connectivity, dtype=np.intp),
        fill_value=-1,
        cf_role="face_node_connectivity",
        original_start_index=0,
    )
    mesh = Mesh2d(
        node_x=np.asarray(node_x, dtype=np.float64),
        node_y=np.asarray(node_y, dtype=np.float64),
        face_node_connectivity=fnc,
    )

    data_variables: dict[str, MeshVariable] = {}
    topo_data_vars: dict[str, str] = {}
    if data is not None:
        if data_locations is None:
            data_locations = {}
        for name, arr in data.items():
            loc = data_locations.get(name, "face")
            topo_data_vars[name] = loc
            data_variables[name] = MeshVariable(
                name=name,
                location=loc,
                mesh_name=mesh_name,
                shape=arr.shape,
                _data=arr,
            )

    srs = sr_from_epsg(epsg)
    crs_wkt = srs.ExportToWkt()

    topo_info = MeshTopologyInfo(
        mesh_name=mesh_name,
        topology_dimension=2,
        node_x_var=f"{mesh_name}_node_x",
        node_y_var=f"{mesh_name}_node_y",
        face_node_var=f"{mesh_name}_face_nodes",
        data_variables=topo_data_vars,
        crs_wkt=crs_wkt,
    )

    result = cls(
        mesh=mesh,
        data_variables=data_variables,
        global_attributes={"Conventions": UGRID_CONVENTIONS},
        topology_info=topo_info,
        crs_wkt=crs_wkt,
    )
    return result

from_structured(dataset, band_names=None, mesh_name=DEFAULT_MESH_NAME) classmethod #

Build a mesh from a raster, one quad face per cell.

The bridge from the structured world: each cell becomes a quad over the corner lattice (shared corners deduplicated) and each band becomes a per-face variable, so a raster can be fed to the mesh operations.

Parameters:

Name Type Description Default
dataset Any

The source raster (a pyramids Dataset / NetCDF variable).

required
band_names list[str] | None

Names for the per-face variables, one per band. Defaults to band_1, band_2, ….

None
mesh_name str

The topology name to stamp. Defaults to the package default.

DEFAULT_MESH_NAME

Returns:

Name Type Description
UgridDataset UgridDataset

The quad mesh carrying the band values.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def from_structured(
    cls,
    dataset: Any,
    band_names: list[str] | None = None,
    mesh_name: str = DEFAULT_MESH_NAME,
) -> UgridDataset:
    """Build a mesh from a raster, one quad face per cell.

    The bridge from the structured world: each cell becomes a quad over the corner
    lattice (shared corners deduplicated) and each band becomes a per-face variable, so a
    raster can be fed to the mesh operations.

    Args:
        dataset: The source raster (a pyramids ``Dataset`` / ``NetCDF`` variable).
        band_names: Names for the per-face variables, one per band. Defaults to
            ``band_1``, ``band_2``, ….
        mesh_name: The topology name to stamp. Defaults to the package default.

    Returns:
        UgridDataset: The quad mesh carrying the band values.
    """
    node_x, node_y, faces, data = _construct.from_structured(dataset, band_names)
    return cls.from_arrays(
        node_x,
        node_y,
        faces,
        data=data,
        epsg=dataset.epsg,
        mesh_name=mesh_name,
    )

from_geodataframe(gdf, mesh_name=DEFAULT_MESH_NAME) classmethod #

Build a mesh from polygon geometries, one face per polygon.

Vertices are deduplicated into the node set and each ring is oriented counter-clockwise; the frame's attribute columns become per-face variables.

Parameters:

Name Type Description Default
gdf Any

A GeoDataFrame of polygons. Its crs is carried onto the mesh verbatim, so a projected CRS stays projected even when it has no EPSG code.

required
mesh_name str

The topology name to stamp. Defaults to the package default.

DEFAULT_MESH_NAME

Returns:

Name Type Description
UgridDataset UgridDataset

The mesh built from the polygons.

Raises:

Type Description
ValueError

The frame declares no CRS, so the mesh would carry no georeferencing.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def from_geodataframe(
    cls, gdf: Any, mesh_name: str = DEFAULT_MESH_NAME
) -> UgridDataset:
    """Build a mesh from polygon geometries, one face per polygon.

    Vertices are deduplicated into the node set and each ring is oriented
    counter-clockwise; the frame's attribute columns become per-face variables.

    Args:
        gdf: A GeoDataFrame of polygons. Its ``crs`` is carried onto the mesh verbatim,
            so a projected CRS stays projected even when it has no EPSG code.
        mesh_name: The topology name to stamp. Defaults to the package default.

    Returns:
        UgridDataset: The mesh built from the polygons.

    Raises:
        ValueError: The frame declares no CRS, so the mesh would carry no
            georeferencing.
    """
    node_x, node_y, faces, data = _construct.from_geodataframe(gdf)
    # Carry the frame's own CRS. Reading an EPSG code and defaulting to 4326 stamped degrees
    # on a projected frame whose CRS has no EPSG code, and on a frame with no CRS at all --
    # silent georeferencing corruption, since everything downstream trusts `epsg`.
    crs = getattr(gdf, "crs", None)
    if crs is None:
        raise ValueError(
            "from_geodataframe: the GeoDataFrame declares no CRS, so the mesh would have no "
            "georeferencing. Set `gdf.crs` (e.g. gdf.set_crs(4326)) before converting."
        )
    epsg = crs.to_epsg()
    built = cls.from_arrays(
        node_x,
        node_y,
        faces,
        data=data,
        epsg=epsg if epsg is not None else 4326,
        mesh_name=mesh_name,
    )
    if epsg is not None:
        return built
    # A CRS with no EPSG code (a projected one given as WKT, say) would otherwise be
    # reduced to the 4326 placeholder `from_arrays` needs, stamping degrees on metres.
    # Keep the frame's WKT verbatim instead.
    wkt = crs.to_wkt()
    return cls(
        mesh=built.mesh,
        data_variables=built.data_vars,
        global_attributes={"Conventions": UGRID_CONVENTIONS},
        topology_info=_topology_info_named(mesh_name, crs_wkt=wkt),
        crs_wkt=wkt,
        file_name=None,
    )

from_xarray(ds) classmethod #

Read a mesh back from an xarray.Dataset in the UGRID-CF encoding.

The inverse of :meth:to_xarray. xarray is a peer dependency, imported only inside the bridge, so nothing in this module imports it at module scope.

Parameters:

Name Type Description Default
ds Any

The xarray.Dataset to read.

required

Returns:

Name Type Description
UgridDataset UgridDataset

The reconstructed mesh and variables.

Raises:

Type Description
OptionalPackageDoesNotExist

xarray is not installed.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def from_xarray(cls, ds: Any) -> UgridDataset:
    """Read a mesh back from an ``xarray.Dataset`` in the UGRID-CF encoding.

    The inverse of :meth:`to_xarray`. xarray is a peer dependency, imported only inside
    the bridge, so nothing in this module imports it at module scope.

    Args:
        ds: The ``xarray.Dataset`` to read.

    Returns:
        UgridDataset: The reconstructed mesh and variables.

    Raises:
        OptionalPackageDoesNotExist: xarray is not installed.
    """
    mesh, data_variables = _interop.from_xarray(ds)
    mesh_name = _interop.read_mesh_name(ds)
    return cls(
        mesh=mesh,
        data_variables=data_variables,
        global_attributes={},
        # Keep the topology's own name: without it a mesh called anything other than
        # "mesh2d" came back renamed, and a re-export then wrote the wrong dimensions.
        topology_info=_topology_info_named(mesh_name),
        crs_wkt=_interop.read_crs_wkt(ds),
        file_name=None,
        # Rebuild the ragged volume topology from its companion arrays when present
        # (issue #1330); `None` for a 2-D / uniform mesh, leaving the dense path in force.
        volume_topology=_interop.volume_topology_from_xarray(ds),
    )

from_zarr(store, **kwargs) classmethod #

Read a mesh from a zarr store written by :meth:to_zarr.

Parameters:

Name Type Description Default
store Any

The zarr store (a path or a mapping).

required
**kwargs Any

Passed to xarray.open_zarr.

{}

Returns:

Name Type Description
UgridDataset UgridDataset

The reconstructed mesh and variables.

Raises:

Type Description
OptionalPackageDoesNotExist

xarray or zarr is not installed.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def from_zarr(cls, store: Any, **kwargs: Any) -> UgridDataset:
    """Read a mesh from a zarr store written by :meth:`to_zarr`.

    Args:
        store: The zarr store (a path or a mapping).
        **kwargs: Passed to ``xarray.open_zarr``.

    Returns:
        UgridDataset: The reconstructed mesh and variables.

    Raises:
        OptionalPackageDoesNotExist: xarray or zarr is not installed.
    """
    # One open, read twice: the mesh and the CRS both come off the same dataset, so the
    # store is not opened again just to recover the grid mapping.
    opened = _interop.open_zarr_dataset(store, **kwargs)
    mesh, data_variables = _interop.from_xarray(opened)
    return cls(
        mesh=mesh,
        data_variables=data_variables,
        global_attributes={},
        topology_info=_topology_info_named(_interop.read_mesh_name(opened)),
        crs_wkt=_interop.read_crs_wkt(opened),
        file_name=None,
    )

mesh_names(path, driver=None) staticmethod #

The names of every topology a file declares.

A mesh file may carry several topologies; :meth:read_file takes the first unless told otherwise, so this is how a caller discovers what else is in there.

Dispatch mirrors :meth:read_file exactly, including the short-circuit that keeps a NetCDF suffix from triggering driver discovery. Every driver is asked, not only those declaring multi_mesh: a single-mesh format answers with a one-item list, which is the right answer rather than an error.

Parameters:

Name Type Description Default
path str | Path

Path to the file.

required
driver str | None

Name of a registered driver to ask, bypassing detection. None (the default) resolves as described above.

None

Returns:

Type Description
list[str]

list[str]: One name per declared topology, in file order.

Raises:

Type Description
FileNotFoundError

The file does not exist.

DriverNotExistError

driver names a driver that is not installed.

UnsupportedMeshFormatError

No installed driver claims the suffix and the built-in reader cannot open it either, or a driver failed or returned something other than a list of topology names.

IsADirectoryError

The path is a directory that no driver claims.

RuntimeError

GDAL cannot open a file that reached the built-in reader by its own suffix. GDAL exceptions are enabled package-wide, so the open failure surfaces as GDAL's own error.

ValueError

The file declares no UGRID topology.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@staticmethod
def mesh_names(path: str | Path, driver: str | None = None) -> list[str]:
    """The names of every topology a file declares.

    A mesh file may carry several topologies; :meth:`read_file` takes the first unless told
    otherwise, so this is how a caller discovers what else is in there.

    Dispatch mirrors :meth:`read_file` exactly, including the short-circuit that keeps a
    NetCDF suffix from triggering driver discovery. Every driver is asked, not only those
    declaring ``multi_mesh``: a single-mesh format answers with a one-item list, which is
    the right answer rather than an error.

    Args:
        path: Path to the file.
        driver: Name of a registered driver to ask, bypassing detection. ``None`` (the
            default) resolves as described above.

    Returns:
        list[str]: One name per declared topology, in file order.

    Raises:
        FileNotFoundError: The file does not exist.
        DriverNotExistError: ``driver`` names a driver that is not installed.
        UnsupportedMeshFormatError: No installed driver claims the suffix and the
            built-in reader cannot open it either, or a driver failed or returned
            something other than a list of topology names.
        IsADirectoryError: The path is a directory that no driver claims.
        RuntimeError: GDAL cannot open a file that reached the built-in reader by its own
            suffix. GDAL exceptions are enabled package-wide, so the open failure
            surfaces as GDAL's own error.
        ValueError: The file declares no UGRID topology.
    """
    selected, native = _resolve_read_driver(path, driver)
    if selected is not None:
        result = _mesh_names_through_driver(selected, path)
    else:
        try:
            result = UgridDataset._ugrid_netcdf_mesh_names(
                path, wrap_unreadable=not native
            )
        except NoMeshTopologyError:
            fallback = _netcdf_fallback_driver(path, driver)
            if fallback is None:
                raise
            result = _mesh_names_through_driver(fallback, path)
    return result

open_mfdataset(paths, *, driver=None, mesh_name=None, sort=True) classmethod #

Open many mesh files sharing one topology and stack them along time (#1378).

The many-files entry point. :meth:read_all answers every topology in one file; this answers one topology across many files, which is the shape a long run is written in — one file per day, per month, or per restart.

The topology is read from the first file and every other file must match it; the data variables are concatenated along time by :meth:concat, so the rules about what may be joined are that method's rules, stated in one place.

Parameters:

Name Type Description Default
paths str | Path | Sequence[str | Path]

A glob pattern ("out/*_map.nc"), a single path, or a sequence of paths. A pattern that matches nothing is an error rather than an empty dataset.

required
driver str | None

Name of a registered mesh driver, bypassing detection. None detects.

None
mesh_name str | None

Which topology to take from each file. None takes the first.

None
sort bool

Order the files by their first time stamp before stacking, so a run whose filenames do not sort chronologically still comes back in time order — run_t10 sorts before run_t2 lexically, which a glob would otherwise stack in that order. Only a dated axis can be ordered this way. A file carrying no CF time units reports positional indices, which say nothing about where it belongs, so it keeps its given position even with sort=True: for a set of undated files, pass an explicitly ordered sequence rather than a glob. In a mixed set the dated files are ordered among themselves and placed back into the slots they occupied, so the undated ones do not move. False always keeps the given order.

True

Returns:

Name Type Description
UgridDataset UgridDataset

One dataset on the shared topology, its time axis spanning every

UgridDataset

file in order.

Raises:

Type Description
ValueError

paths is empty, or a glob pattern matches nothing.

AlignmentError

A file sits on a different topology than the first.

See Also

read_all: Every topology within one file. concat: The time-axis join this performs, and its rules.

Examples:

  • Stack a run written one file per day:
    >>> ds = UgridDataset.open_mfdataset("out/*_map.nc")  # doctest: +SKIP
    >>> ds.time_values[0], ds.time_values[-1]  # doctest: +SKIP
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def open_mfdataset(
    cls,
    paths: str | Path | Sequence[str | Path],
    *,
    driver: str | None = None,
    mesh_name: str | None = None,
    sort: bool = True,
) -> UgridDataset:
    """Open many mesh files sharing one topology and stack them along time (#1378).

    The many-**files** entry point. :meth:`read_all` answers every topology in **one**
    file; this answers one topology across many files, which is the shape a long run is
    written in — one file per day, per month, or per restart.

    The topology is read from the first file and every other file must match it; the data
    variables are concatenated along time by :meth:`concat`, so the rules about what may
    be joined are that method's rules, stated in one place.

    Args:
        paths: A glob pattern (``"out/*_map.nc"``), a single path, or a sequence of paths.
            A pattern that matches nothing is an error rather than an empty dataset.
        driver: Name of a registered mesh driver, bypassing detection. ``None`` detects.
        mesh_name: Which topology to take from each file. ``None`` takes the first.
        sort: Order the files by their first time stamp before stacking, so a run whose
            filenames do not sort chronologically still comes back in time order —
            ``run_t10`` sorts before ``run_t2`` lexically, which a glob would otherwise
            stack in that order.
            Only a **dated** axis can be ordered this way. A file carrying no CF time
            units reports positional indices, which say nothing about where it belongs, so
            it keeps its given position even with ``sort=True``: for a set of undated
            files, pass an explicitly ordered sequence rather than a glob. In a mixed set
            the dated files are ordered among themselves and placed back into the slots
            they occupied, so the undated ones do not move.
            ``False`` always keeps the given order.

    Returns:
        UgridDataset: One dataset on the shared topology, its time axis spanning every
        file in order.

    Raises:
        ValueError: ``paths`` is empty, or a glob pattern matches nothing.
        AlignmentError: A file sits on a different topology than the first.

    See Also:
        read_all: Every topology within one file.
        concat: The time-axis join this performs, and its rules.

    Examples:
        - Stack a run written one file per day:
            ```python
            >>> ds = UgridDataset.open_mfdataset("out/*_map.nc")  # doctest: +SKIP
            >>> ds.time_values[0], ds.time_values[-1]  # doctest: +SKIP
            ```
    """
    if isinstance(paths, (str, Path)):
        pattern = str(paths)
        is_pattern = any(character in pattern for character in "*?[")
        matched = sorted(glob(pattern)) if is_pattern else []
        if matched:
            resolved: list[str | Path] = list(matched)
        elif is_pattern:
            raise ValueError(
                f"open_mfdataset() got the pattern {pattern!r}, which matches no file."
            )
        else:
            resolved = [paths]
    else:
        resolved = list(paths)
    if not resolved:
        raise ValueError(
            "open_mfdataset() got an empty list of paths; there is nothing to open."
        )
    datasets = [
        cls.read_file(path, driver=driver, mesh_name=mesh_name) for path in resolved
    ]
    if sort:
        # A run's filenames need not sort chronologically (`run_t10` sorts before
        # `run_t2`), so order by what the data says instead. Only a *dated* axis can be
        # ordered: a file carrying no CF time units reports positional indices, which say
        # nothing about where it belongs.
        #
        # So the dated files are sorted *among themselves* and dropped back into the slots
        # they occupied, leaving every undated file exactly where it was given. Sorting the
        # whole list with undated files pushed to one end would move them, which is what
        # this method's own docstring promises not to do.
        dated_slots = [
            index
            for index, dataset in enumerate(datasets)
            if dataset.time_values
            and any(
                TIME_UNITS_ATTR in var.attributes
                for var in dataset._data_variables.values()
            )
        ]

        def first_stamp(dataset: UgridDataset) -> tuple:
            """The sort key of a dated dataset: its earliest stamp."""
            stamps = dataset.time_values
            # `dated_slots` holds only datasets whose `time_values` is non-empty, which
            # the type checker cannot see from the comprehension above.
            assert stamps is not None
            return _stamp_order(stamps[0])

        ordered = sorted(
            (datasets[index] for index in dated_slots), key=first_stamp
        )
        for slot, dataset in zip(dated_slots, ordered, strict=True):
            datasets[slot] = dataset
    head, *rest = datasets
    return head.concat(rest) if rest else head

read_all(path, driver=None, lazy=True) classmethod #

Read every topology in a file, one dataset each.

:meth:read_file answers a single mesh (the first, or the one named). This answers all of them, so nothing in a multi-mesh file is silently dropped. Dispatch follows :meth:mesh_names and :meth:read_file, so a third-party format works here too.

Parameters:

Name Type Description Default
path str | Path

Path to the file.

required
driver str | None

Name of a registered mesh driver to use, bypassing detection. None (the default) detects.

None
lazy bool

Defer reading variable values until first access. Forwarded to a driver, which may honour an eager read; the built-in UGRID reader has no eager mode, so lazy=False on a native read raises :class:TypeError, exactly as :meth:read_file does. Without it a multi-topology third-party format could only ever be read lazily.

True

Returns:

Type Description
dict[str, UgridDataset]

dict[str, UgridDataset]: Each topology name mapped to its dataset.

Raises:

Type Description
FileNotFoundError

The file does not exist.

DriverNotExistError

driver names a driver that is not installed.

UnsupportedMeshFormatError

No installed driver reads the file and the built-in reader cannot either — raised from :meth:mesh_names, which this delegates to, so every error that method raises surfaces here too.

IsADirectoryError

The path is a directory that no driver claims.

RuntimeError

GDAL cannot open a file that reached the built-in reader by its own suffix. GDAL exceptions are enabled package-wide, so the open failure surfaces as GDAL's own error.

TypeError

lazy=False on a native (built-in UGRID) read, which has no eager mode -- the same rejection :meth:read_file makes.

ValueError

The file declares no UGRID topology.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def read_all(
    cls, path: str | Path, driver: str | None = None, lazy: bool = True
) -> dict[str, UgridDataset]:
    """Read **every** topology in a file, one dataset each.

    :meth:`read_file` answers a single mesh (the first, or the one named). This answers
    all of them, so nothing in a multi-mesh file is silently dropped. Dispatch follows
    :meth:`mesh_names` and :meth:`read_file`, so a third-party format works here too.

    Args:
        path: Path to the file.
        driver: Name of a registered **mesh** driver to use, bypassing detection.
            ``None`` (the default) detects.
        lazy: Defer reading variable values until first access. Forwarded to a driver,
            which may honour an eager read; the built-in UGRID reader has no eager mode, so
            ``lazy=False`` on a native read raises :class:`TypeError`, exactly as
            :meth:`read_file` does. Without it a multi-topology third-party format could
            only ever be read lazily.

    Returns:
        dict[str, UgridDataset]: Each topology name mapped to its dataset.

    Raises:
        FileNotFoundError: The file does not exist.
        DriverNotExistError: ``driver`` names a driver that is not installed.
        UnsupportedMeshFormatError: No installed driver reads the file and the built-in
            reader cannot either — raised from :meth:`mesh_names`, which this delegates
            to, so every error that method raises surfaces here too.
        IsADirectoryError: The path is a directory that no driver claims.
        RuntimeError: GDAL cannot open a file that reached the built-in reader by its own
            suffix. GDAL exceptions are enabled package-wide, so the open failure
            surfaces as GDAL's own error.
        TypeError: ``lazy=False`` on a native (built-in UGRID) read, which has no eager
            mode -- the same rejection :meth:`read_file` makes.
        ValueError: The file declares no UGRID topology.
    """
    # Resolve once, for real. Passing a driver *name* through only short-circuited the
    # route where detection had found something: when nothing claimed the suffix the name
    # was None, so `mesh_names` and every per-topology read re-ran full detection anyway
    # -- measured at two `can_open` calls for one `read_all`, growing per topology.
    # Threading the resolved object through covers the fallback route too.
    selected, native = _resolve_read_driver(path, driver)
    # Set in the native branch below; stays empty whenever a driver handles the file --
    # resolved up front, or picked by the fallback -- in which case it is never read.
    native_names: list[str] = []
    if selected is None:
        try:
            native_names = cls._ugrid_netcdf_mesh_names(
                path, wrap_unreadable=not native
            )
        except NoMeshTopologyError:
            # The file opened as NetCDF but declares no UGRID topology; fall back to a
            # driver claiming the suffix, as read_file does. If none claims it, the
            # original error stands.
            selected = _netcdf_fallback_driver(path, driver)
            if selected is None:
                raise
    if selected is None:
        result = {
            name: cls._read_ugrid_netcdf(
                path, name, wrap_unreadable=not native, lazy=lazy
            )
            for name in native_names
        }
    else:
        names = _mesh_names_through_driver(selected, path)
        result = {
            name: _read_through_driver(selected, path, name, cls, lazy)
            for name in names
        }
    return result

isel_layer(index) #

Select along the layer axis by position.

A layered variable — (layer, element), or (time, layer, element) — is indexed on its layer axis. An integer collapses that axis (the variable loses its layer dimension); a slice or sequence keeps it, trimmed. Variables with no layer axis are carried through untouched, as the time selectors carry static variables.

For a ragged 3-D mesh (:attr:volume_topology set) a location="volume" variable has no rectangular layer axis to index; the selection is per column instead. index must be an int k: each column yields its k-th layer where it has one, and a column shallower than k + 1 layers yields NaN — the absent layers are made explicit, never padded silently. The volume variable becomes a plain location="face" field; other variables carry through as on the uniform path.

Parameters:

Name Type Description Default
index int | slice | list[int] | ndarray

An int layer, a slice, or a sequence of layer positions. A ragged mesh accepts only an int.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with the layer selection applied.

Raises:

Type Description
ValueError

No variable has a layer dimension, or a non-int index was given for a ragged mesh.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def isel_layer(self, index: int | slice | list[int] | np.ndarray) -> UgridDataset:
    """Select along the layer axis by position.

    A layered variable — ``(layer, element)``, or ``(time, layer, element)`` — is indexed
    on its layer axis. An integer collapses that axis (the variable loses its layer
    dimension); a slice or sequence keeps it, trimmed. Variables with no layer axis are
    carried through untouched, as the time selectors carry static variables.

    For a **ragged** 3-D mesh (:attr:`volume_topology` set) a ``location="volume"``
    variable has no rectangular layer axis to index; the selection is per column instead.
    ``index`` must be an ``int`` ``k``: each column yields its ``k``-th layer where it has
    one, and a column shallower than ``k + 1`` layers yields NaN — the absent layers are
    made explicit, never padded silently. The volume variable becomes a plain
    ``location="face"`` field; other variables carry through as on the uniform path.

    Args:
        index: An ``int`` layer, a ``slice``, or a sequence of layer positions. A ragged
            mesh accepts only an ``int``.

    Returns:
        UgridDataset: A new dataset with the layer selection applied.

    Raises:
        ValueError: No variable has a layer dimension, or a non-``int`` ``index`` was given
            for a ragged mesh.
    """
    if self._volume_topology is not None:
        return self._isel_layer_ragged(index)
    new_vars: dict[str, MeshVariable] = {}
    layered = False
    for name, var in self._data_variables.items():
        axis = self._layer_axis(var)
        if axis is None:
            new_vars[name] = var
            continue
        layered = True
        data = np.asarray(var.data)
        if isinstance(index, (int, np.integer)):
            picked = np.take(data, int(index), axis=axis)
            moved = var.with_data(picked)
            moved.dimensions = tuple(
                dim
                for position, dim in enumerate(var.dimensions)
                if position != axis
            )
        else:
            positions = (
                np.arange(data.shape[axis])[index]
                if isinstance(index, slice)
                else np.asarray(index, dtype=np.intp)
            )
            moved = var.with_data(np.take(data, positions, axis=axis))
        new_vars[name] = moved
    if not layered:
        raise ValueError(
            "isel_layer needs at least one variable with a layer dimension; this "
            "dataset has none."
        )
    return self._rebuild(new_vars)

sel_layer(value) #

Select along the layer axis by coordinate value.

Matches value against :attr:layer_values, falling back to layer positions when no layer coordinate is present -- which is the usual case, since the reader does not populate layer_values (see :attr:layer_values). So on a mesh read from a file, sel_layer(1) selects layer position 1.

Parameters:

Name Type Description Default
value Any

The layer coordinate value to select.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with that layer selected.

Raises:

Type Description
ValueError

No layer dimension, or the value is not among the layer coordinates.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sel_layer(self, value: Any) -> UgridDataset:
    """Select along the layer axis by coordinate value.

    Matches ``value`` against :attr:`layer_values`, falling back to layer positions when
    no layer coordinate is present -- which is the usual case, since the reader does not
    populate `layer_values` (see :attr:`layer_values`). So on a mesh read from a file,
    ``sel_layer(1)`` selects layer position 1.

    Args:
        value: The layer coordinate value to select.

    Returns:
        UgridDataset: A new dataset with that layer selected.

    Raises:
        ValueError: No layer dimension, or the value is not among the layer coordinates.
    """
    count = self.n_layers
    if count is None:
        raise ValueError(
            "sel_layer needs at least one variable with a layer dimension; this "
            "dataset has none."
        )
    # Read the property once: it walks every variable, so evaluating it twice walked
    # them twice.
    stored = self.layer_values
    coords = stored if stored is not None else list(range(count))
    if value not in coords:
        raise ValueError(
            f"sel_layer: layer value {value!r} not found in the layer coordinate "
            f"{coords!r}."
        )
    return self.isel_layer(coords.index(value))

collapse_layer(layer, *, location='face') #

Collapse a ragged 3-D mesh's volume variables to a 2-D field (issue #1330).

The explicit 2-D collapse of a ragged mesh: each column's layer-th value becomes a plain (n_face,) (or (time, n_face)) face field, absent layers NaN. It is :meth:isel_layer under a name that says "give me a 2-D slice", so a caller can ask for the surface/bed layer as a flat field without reaching for the per-column internals. (Named collapse_layer rather than to_location because the latter already moves a variable between mesh locations by graph interpolation — a different operation.)

Parameters:

Name Type Description Default
layer int

The 0-based layer position to take from each column.

required
location str

The target mesh location. Only "face" is supported — a ragged volume collapses onto its columns' faces. Defaults to "face".

'face'

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose volume variables are 2-D face fields.

Raises:

Type Description
ValueError

location is not "face", or the dataset has no volume topology to collapse.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def collapse_layer(self, layer: int, *, location: str = "face") -> UgridDataset:
    """Collapse a ragged 3-D mesh's ``volume`` variables to a 2-D field (issue #1330).

    The explicit 2-D collapse of a ragged mesh: each column's ``layer``-th value becomes a
    plain ``(n_face,)`` (or ``(time, n_face)``) face field, absent layers NaN. It is
    :meth:`isel_layer` under a name that says "give me a 2-D slice", so a caller can ask for
    the surface/bed layer as a flat field without reaching for the per-column internals.
    (Named ``collapse_layer`` rather than ``to_location`` because the latter already moves a
    variable *between* mesh locations by graph interpolation — a different operation.)

    Args:
        layer: The 0-based layer position to take from each column.
        location: The target mesh location. Only ``"face"`` is supported — a ragged volume
            collapses onto its columns' faces. Defaults to ``"face"``.

    Returns:
        UgridDataset: A new dataset whose volume variables are 2-D face fields.

    Raises:
        ValueError: ``location`` is not ``"face"``, or the dataset has no volume topology
            to collapse.
    """
    if self._volume_topology is None:
        raise ValueError(
            "collapse_layer needs a ragged volume topology; this dataset has none (it is "
            "2-D or uniformly layered). Use isel_layer for a uniform mesh."
        )
    if location != "face":
        raise ValueError(
            f"collapse_layer supports only 'face' for a ragged volume mesh, not "
            f"{location!r}."
        )
    return self._isel_layer_ragged(int(layer))

to_dataframe(variables=None, *, dropna=False) #

A tidy frame of the mesh values, one row per element (and step).

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.to_dataframe, in the tidy shape rather than the raster (y, x) MultiIndex one: an unstructured element has no row/column address, so each row carries the element index, its centroid coordinates, the time step where the variable has one, and the value.

Parameters:

Name Type Description Default
variables Sequence[str] | None

Which data variables to include. None (the default) takes them all.

None
dropna bool

Drop rows whose value is no-data. Defaults to False.

False

Returns:

Type Description
DataFrame

pandas.DataFrame: Columns variable, element, x, y, layer,

DataFrame

time and value. element indexes the facet the variable sits on and

DataFrame

x/y are that facet's coordinates, so a node variable is addressed by node.

DataFrame

layer is the layer coordinate, or None for an unlayered variable, and time

DataFrame

the step coordinate, or None for a static one.

Raises:

Type Description
KeyError

A requested variable is not a data variable of this dataset.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_dataframe(
    self, variables: Sequence[str] | None = None, *, dropna: bool = False
) -> pd.DataFrame:
    """A tidy frame of the mesh values, one row per element (and step).

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.to_dataframe`, in the **tidy**
    shape rather than the raster ``(y, x)`` MultiIndex one: an unstructured element has no
    row/column address, so each row carries the element index, its centroid coordinates,
    the time step where the variable has one, and the value.

    Args:
        variables: Which data variables to include. ``None`` (the default) takes them all.
        dropna: Drop rows whose value is no-data. Defaults to False.

    Returns:
        pandas.DataFrame: Columns ``variable``, ``element``, ``x``, ``y``, ``layer``,
        ``time`` and ``value``. ``element`` indexes the facet the variable sits on and
        ``x``/``y`` are that facet's coordinates, so a node variable is addressed by node.
        ``layer`` is the layer coordinate, or None for an unlayered variable, and ``time``
        the step coordinate, or None for a static one.

    Raises:
        KeyError: A requested variable is not a data variable of this dataset.
    """
    names = list(self._data_variables) if variables is None else list(variables)
    frames: list[pd.DataFrame] = []
    for name in names:
        if name not in self._data_variables:
            raise KeyError(name)
        var = self._data_variables[name]
        if var.data is None:
            continue
        frames.extend(self._variable_frames(name, var))
    if not frames:
        # Match the populated frame's dtypes, so a caller that concatenates or
        # dtype-checks sees one schema either way.
        return pd.DataFrame(
            {
                "variable": pd.Series(dtype="str"),
                "element": pd.Series(dtype="int64"),
                "x": pd.Series(dtype="float64"),
                "y": pd.Series(dtype="float64"),
                "layer": pd.Series(dtype="object"),
                "time": pd.Series(dtype="object"),
                "value": pd.Series(dtype="float64"),
            }
        )
    frame = pd.concat(frames, ignore_index=True)
    if dropna:
        frame = frame[~frame["value"].isna()].reset_index(drop=True)
    return frame

copy() #

An independent deep copy of this dataset.

Every variable's values are copied, so writing into the copy never shows in the original — the counterpart of :meth:pyramids.netcdf.NetCDF.copy.

Returns:

Name Type Description
UgridDataset UgridDataset

The copy.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def copy(self) -> UgridDataset:
    """An independent deep copy of this dataset.

    Every variable's values are copied, so writing into the copy never shows in the
    original — the counterpart of :meth:`pyramids.netcdf.NetCDF.copy`.

    Returns:
        UgridDataset: The copy.
    """
    copied: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        copied[name] = (
            var
            if var.data is None
            else var.with_data(np.array(var.data, copy=True))
        )
    return type(self)(
        mesh=self._mesh,
        data_variables=copied,
        global_attributes=dict(self._global_attributes),
        topology_info=self._topology_info,
        crs_wkt=self._crs_wkt,
        file_name=self._file_name,
        volume_topology=self._volume_topology,
    )

from_bytes(data, *, suffix='.nc') classmethod #

Read a UGRID mesh from an in-memory buffer.

Writes data into GDAL's in-memory filesystem and reads it as a file, mirroring :meth:pyramids.netcdf.NetCDF.from_bytes — for a mesh fetched over the network or held in a database blob. The values are materialised before the buffer is unlinked, so the result does not depend on it.

Parameters:

Name Type Description Default
data bytes

The bytes of a UGRID NetCDF file.

required
suffix str

The extension to present to GDAL. Defaults to ".nc".

'.nc'

Returns:

Name Type Description
UgridDataset UgridDataset

The mesh read from the buffer.

Raises:

Type Description
RuntimeError

GDAL cannot read the buffer at all. It is written to /vsimem and read through :meth:read_file, so GDAL's own error comes back -- naming the in-memory path rather than the caller's bytes.

ValueError

The buffer reads as a file but declares no UGRID topology.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@classmethod
def from_bytes(cls, data: bytes, *, suffix: str = ".nc") -> UgridDataset:
    """Read a UGRID mesh from an in-memory buffer.

    Writes ``data`` into GDAL's in-memory filesystem and reads it as a file, mirroring
    :meth:`pyramids.netcdf.NetCDF.from_bytes` — for a mesh fetched over the network or
    held in a database blob. The values are materialised before the buffer is unlinked, so
    the result does not depend on it.

    Args:
        data: The bytes of a UGRID NetCDF file.
        suffix: The extension to present to GDAL. Defaults to ``".nc"``.

    Returns:
        UgridDataset: The mesh read from the buffer.

    Raises:
        RuntimeError: GDAL cannot read the buffer at all. It is written to ``/vsimem`` and
            read through :meth:`read_file`, so GDAL's own error comes back -- naming the
            in-memory path rather than the caller's bytes.
        ValueError: The buffer reads as a file but declares no UGRID topology.
    """
    name = f"/vsimem/pyramids_ugrid_{uuid4().hex}{suffix}"
    gdal.FileFromMemBuffer(name, data)
    try:
        result = cls.read_file(name).copy()
    finally:
        gdal.Unlink(name)
    return result

info(buf=None, drivers=False) #

Print a summary of the mesh, its variables and its attributes.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.info: one readable block naming the topology, the element counts, the CRS, and every data variable with its location, dtype and shape.

Parameters:

Name Type Description Default
buf Any

Where to write. Defaults to sys.stdout.

None
drivers bool

Also list the mesh file-format drivers available in this interpreter — the built-in UGRID reader plus any installed plugin. Off by default because resolving them walks every installed distribution, which a summary of one dataset should not pay for.

False
Source code in src/pyramids/netcdf/ugrid/dataset.py
def info(self, buf: Any = None, drivers: bool = False) -> None:
    """Print a summary of the mesh, its variables and its attributes.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.info`: one readable block naming
    the topology, the element counts, the CRS, and every data variable with its location,
    dtype and shape.

    Args:
        buf: Where to write. Defaults to ``sys.stdout``.
        drivers: Also list the mesh file-format drivers available in this interpreter —
            the built-in UGRID reader plus any installed plugin. Off by default because
            resolving them walks every installed distribution, which a summary of one
            dataset should not pay for.
    """
    stream = sys.stdout if buf is None else buf
    lines = [
        f"UgridDataset: {self.mesh_name}",
        f"  nodes: {self.n_node}  faces: {self.n_face}  edges: {self.n_edge}",
        f"  epsg: {self.epsg}",
        f"  variables ({len(self._data_variables)}):",
    ]
    for name, var in self._data_variables.items():
        # Metadata only: `var.data` would fire the lazy loader and pull every variable's
        # full array off disk, which is the opposite of what a summary is for. The declared
        # shape and `has_data_source` answer the same questions without a read.
        shape = str(tuple(var.shape)) if var.has_data_source else "unloaded"
        temporal = "temporal" if var.has_time else "static"
        lines.append(
            f"    {name}: location={var.location} dtype={var.dtype} "
            f"shape={shape} ({temporal})"
        )
    if self._global_attributes:
        lines.append(f"  global attributes ({len(self._global_attributes)}):")
        lines.extend(
            f"    {key}: {value}" for key, value in self._global_attributes.items()
        )
    if drivers:
        driver_lines = describe_drivers()
        # Count the plugins, not the lines: reporting "mesh drivers (1)" on a bare install
        # counted the built-in reader as a driver, while DriverNotExistError described the
        # same state as having none installed.
        plugins = len(driver_lines) - 1
        suffix = "" if plugins == 1 else "s"
        lines.append(f"  mesh drivers (built-in + {plugins} plugin{suffix}):")
        lines.extend(f"    {line}" for line in driver_lines)
    stream.write("\n".join(lines) + "\n")

set_global_attribute(name, value) #

Return a new dataset carrying one more global attribute.

A UGRID derivation is immutable here (as :meth:with_variable is), so this answers a new dataset rather than writing in place; :meth:to_file then persists the attributes through the shared CF writer.

Parameters:

Name Type Description Default
name str

The attribute name.

required
value Any

The attribute value.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose global attributes include name.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def set_global_attribute(self, name: str, value: Any) -> UgridDataset:
    """Return a new dataset carrying one more global attribute.

    A UGRID derivation is immutable here (as :meth:`with_variable` is), so this answers a
    new dataset rather than writing in place; :meth:`to_file` then persists the attributes
    through the shared CF writer.

    Args:
        name: The attribute name.
        value: The attribute value.

    Returns:
        UgridDataset: A new dataset whose global attributes include ``name``.
    """
    return type(self)(
        mesh=self._mesh,
        data_variables=dict(self._data_variables),
        global_attributes={**self._global_attributes, name: value},
        topology_info=self._topology_info,
        crs_wkt=self._crs_wkt,
        file_name=self._file_name,
        volume_topology=self._volume_topology,
    )

delete_global_attribute(name) #

Return a new dataset without the global attribute name.

Parameters:

Name Type Description Default
name str

The attribute to drop. Dropping an absent attribute is not an error, mirroring the raster delete_global_attribute.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset without that attribute.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def delete_global_attribute(self, name: str) -> UgridDataset:
    """Return a new dataset without the global attribute ``name``.

    Args:
        name: The attribute to drop. Dropping an absent attribute is not an error,
            mirroring the raster ``delete_global_attribute``.

    Returns:
        UgridDataset: A new dataset without that attribute.
    """
    remaining = {
        key: value for key, value in self._global_attributes.items() if key != name
    }
    return type(self)(
        mesh=self._mesh,
        data_variables=dict(self._data_variables),
        global_attributes=remaining,
        topology_info=self._topology_info,
        crs_wkt=self._crs_wkt,
        file_name=self._file_name,
        volume_topology=self._volume_topology,
    )

active_mask(variable_name) #

The variable's per-element active (wet/dry) mask, or None when it has none.

The first-class companion of the data (issue #1331): True marks an active/wet element, False a dry one, kept separate from nodata/NaN so a consumer can tell a dry element from a missing value. The mask is element-indexed — (n_element,) when it is static or (n_time, n_element) when it varies per step — and is returned as read, never applied to the values. Use :meth:masked_values to get the values with it applied.

Parameters:

Name Type Description Default
variable_name str

Name of the data variable.

required

Returns:

Type Description
NDArray | None

np.ndarray | None: The boolean mask, or None when the variable carries none.

Raises:

Type Description
KeyError

variable_name is not a data variable of this dataset.

Examples:

  • A variable with a mask reports it; one without answers None:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> ds = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"depth": np.array([2.0, 4.0])},
    ... )
    >>> ds["depth"].active = np.array([True, False])
    >>> ds.active_mask("depth").tolist()
    [True, False]
    >>> ds.active_mask("depth") is not None
    True
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def active_mask(self, variable_name: str) -> np.typing.NDArray | None:
    """The variable's per-element active (wet/dry) mask, or ``None`` when it has none.

    The first-class companion of the data (issue #1331): ``True`` marks an active/wet
    element, ``False`` a dry one, kept separate from ``nodata``/NaN so a consumer can tell
    a dry element from a missing value. The mask is element-indexed — ``(n_element,)``
    when it is static or ``(n_time, n_element)`` when it varies per step — and is returned
    as read, never applied to the values. Use :meth:`masked_values` to get the values with
    it applied.

    Args:
        variable_name: Name of the data variable.

    Returns:
        np.ndarray | None: The boolean mask, or ``None`` when the variable carries none.

    Raises:
        KeyError: ``variable_name`` is not a data variable of this dataset.

    Examples:
        - A variable with a mask reports it; one without answers ``None``:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> ds = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"depth": np.array([2.0, 4.0])},
            ... )
            >>> ds["depth"].active = np.array([True, False])
            >>> ds.active_mask("depth").tolist()
            [True, False]
            >>> ds.active_mask("depth") is not None
            True

            ```
    """
    var = self.get_data(variable_name)
    return None if var.active is None else np.asarray(var.active, dtype=bool)

masked_values(variable_name) #

The variable's values with both nodata and the active mask blanked to NaN.

The opt-in counterpart of a bare .data read (issue #1331): dry elements (where :meth:active_mask is False) become NaN on top of the usual nodata blanking, so a caller that wants "treat dry as missing" gets it explicitly — the values are never masked by default. Keeps the variable's full shape (every time step and layer), unlike the single-step :meth:sample / :meth:weighted path. When the variable has no mask the result is just the nodata-blanked values.

Parameters:

Name Type Description Default
variable_name str

Name of the data variable.

required

Returns:

Type Description
NDArray

np.ndarray: The float64 values, dry and missing elements alike as NaN.

Raises:

Type Description
KeyError

variable_name is not a data variable of this dataset.

ValueError

The variable has no loaded data.

Examples:

  • Dry elements become NaN, so a mean over the wet cells is straightforward:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> ds = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"depth": np.array([2.0, 4.0])},
    ... )
    >>> ds["depth"].active = np.array([True, False])
    >>> ds.masked_values("depth").tolist()
    [2.0, nan]
    >>> float(np.nanmean(ds.masked_values("depth")))
    2.0
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def masked_values(self, variable_name: str) -> np.typing.NDArray:
    """The variable's values with both ``nodata`` **and** the active mask blanked to NaN.

    The **opt-in** counterpart of a bare ``.data`` read (issue #1331): dry elements (where
    :meth:`active_mask` is ``False``) become NaN on top of the usual ``nodata`` blanking,
    so a caller that wants "treat dry as missing" gets it explicitly — the values are
    never masked by default. Keeps the variable's full shape (every time step and layer),
    unlike the single-step :meth:`sample` / :meth:`weighted` path. When the variable has no
    mask the result is just the ``nodata``-blanked values.

    Args:
        variable_name: Name of the data variable.

    Returns:
        np.ndarray: The float64 values, dry and missing elements alike as NaN.

    Raises:
        KeyError: ``variable_name`` is not a data variable of this dataset.
        ValueError: The variable has no loaded data.

    Examples:
        - Dry elements become NaN, so a mean over the wet cells is straightforward:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> ds = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"depth": np.array([2.0, 4.0])},
            ... )
            >>> ds["depth"].active = np.array([True, False])
            >>> ds.masked_values("depth").tolist()
            [2.0, nan]
            >>> float(np.nanmean(ds.masked_values("depth")))
            2.0

            ```
    """
    var = self.get_data(variable_name)
    data = var.data
    if data is None:
        raise ValueError(f"Variable {variable_name!r} has no loaded data.")
    values = gaps_as_nan(np.asarray(data), var.nodata)
    if var.active is not None:
        values = _apply_active_mask(var, values)
    return cast("np.typing.NDArray", values)

summary(variables=None, *, metrics=DEFAULT_METRICS, skipna=True, ddof=0) #

A per-variable summary table over the whole mesh.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.summary, built on the same shared assembly (:func:pyramids.base._summary.variable_summary) so the two classes answer in an identical shape. Each variable is reduced over all of its samples — every element and, for a temporal variable, every step — with the declared no-data value left out.

Parameters:

Name Type Description Default
variables Sequence[str] | None

Which data variables to summarise, in output-row order. None (the default) takes every data variable. An unknown name raises KeyError.

None
metrics Sequence[str]

Which statistics to report, in column order. Defaults to ("count", "min", "max", "mean", "std"); median / var / sum / prod are available too.

DEFAULT_METRICS
skipna bool

Leave no-data out of the statistics (the default) or let it propagate.

True
ddof int

Delta degrees of freedom for std / var. Defaults to 0.

0

Returns:

Type Description
DataFrame

pandas.DataFrame: One row per variable (index name "variable"), one column per

DataFrame

metric. count is int64; the rest are float64. A variable with no valid

DataFrame

element yields NaN statistics and a count of 0.

Raises:

Type Description
KeyError

A requested variable is not a data variable of this dataset.

TypeError

A requested variable is non-numeric.

ValueError

A requested variable has no loaded data, or an unknown metric.

Examples:

  • Per-variable summary of a two-triangle mesh:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"depth": np.array([2.0, 4.0])},
    ... )
    >>> mesh.summary().loc["depth", ["count", "min", "max", "mean"]].tolist()
    [2.0, 2.0, 4.0, 3.0]
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def summary(
    self,
    variables: Sequence[str] | None = None,
    *,
    metrics: Sequence[str] = DEFAULT_METRICS,
    skipna: bool = True,
    ddof: int = 0,
) -> pd.DataFrame:
    """A per-variable summary table over the whole mesh.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.summary`, built on the same shared
    assembly (:func:`pyramids.base._summary.variable_summary`) so the two classes answer in an
    identical shape. Each variable is reduced over **all** of its samples — every element and,
    for a temporal variable, every step — with the declared no-data value left out.

    Args:
        variables: Which data variables to summarise, in output-row order. ``None`` (the
            default) takes every data variable. An unknown name raises ``KeyError``.
        metrics: Which statistics to report, in column order. Defaults to
            ``("count", "min", "max", "mean", "std")``; ``median`` / ``var`` / ``sum`` /
            ``prod`` are available too.
        skipna: Leave no-data out of the statistics (the default) or let it propagate.
        ddof: Delta degrees of freedom for ``std`` / ``var``. Defaults to 0.

    Returns:
        pandas.DataFrame: One row per variable (index name ``"variable"``), one column per
        metric. ``count`` is ``int64``; the rest are ``float64``. A variable with no valid
        element yields NaN statistics and a ``count`` of 0.

    Raises:
        KeyError: A requested variable is not a data variable of this dataset.
        TypeError: A requested variable is non-numeric.
        ValueError: A requested variable has no loaded data, or an unknown metric.

    Examples:
        - Per-variable summary of a two-triangle mesh:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"depth": np.array([2.0, 4.0])},
            ... )
            >>> mesh.summary().loc["depth", ["count", "min", "max", "mean"]].tolist()
            [2.0, 2.0, 4.0, 3.0]

            ```
    """
    names = list(self._data_variables) if variables is None else list(variables)
    arrays: dict[str, np.typing.NDArray] = {}
    for name in names:
        if name not in self._data_variables:
            raise KeyError(name)
        var = self._data_variables[name]
        if var.data is None:
            raise ValueError(f"Variable {name!r} has no loaded data.")
        data = np.asarray(var.data)
        if not np.issubdtype(data.dtype, np.number):
            if variables is None:
                warnings.warn(
                    f"skipping non-numeric variable {name!r} in summary",
                    stacklevel=2,
                )
                continue
            raise TypeError(f"variable {name!r} is non-numeric; cannot summarise")
        arrays[name] = gaps_as_nan(data, var.nodata)
    return variable_summary(arrays, metrics=metrics, skipna=skipna, ddof=ddof)

sample(variable_name, x, y, *, method='contains', time_index=0) #

Sample a mesh variable at point locations.

The mesh counterpart of :meth:pyramids.dataset.Dataset.sample. Where the raster version inverts an affine geotransform to find the pixel under each point, a mesh resolves the point to an element through :class:MeshSpatialIndex: a face-located variable by which face contains the point (method="contains") or the nearest face centroid (method="nearest"); a node-located variable by nearest node.

Parameters:

Name Type Description Default
variable_name str

Name of the data variable.

required
x float | ndarray

Query x-coordinate(s), in the mesh CRS.

required
y float | ndarray

Query y-coordinate(s), in the mesh CRS.

required
method str

"contains" (point-in-face, face variables only) or "nearest". Defaults to "contains".

'contains'
time_index int

Step for a temporal variable. Defaults to 0.

0

Returns:

Type Description
NDArray

numpy.ndarray: One value per query point; NaN where a "contains" query

NDArray

falls outside every face.

Raises:

Type Description
ValueError

An unknown method, "contains" on a non-face variable, or a variable located on edges (unsupported).

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sample(
    self,
    variable_name: str,
    x: float | np.ndarray,
    y: float | np.ndarray,
    *,
    method: str = "contains",
    time_index: int = 0,
) -> np.typing.NDArray:
    """Sample a mesh variable at point locations.

    The mesh counterpart of :meth:`pyramids.dataset.Dataset.sample`. Where the raster
    version inverts an affine geotransform to find the pixel under each point, a mesh
    resolves the point to an element through :class:`MeshSpatialIndex`: a face-located
    variable by which face contains the point (``method="contains"``) or the nearest
    face centroid (``method="nearest"``); a node-located variable by nearest node.

    Args:
        variable_name: Name of the data variable.
        x: Query x-coordinate(s), in the mesh CRS.
        y: Query y-coordinate(s), in the mesh CRS.
        method: ``"contains"`` (point-in-face, face variables only) or ``"nearest"``.
            Defaults to ``"contains"``.
        time_index: Step for a temporal variable. Defaults to 0.

    Returns:
        numpy.ndarray: One value per query point; NaN where a ``"contains"`` query
        falls outside every face.

    Raises:
        ValueError: An unknown ``method``, ``"contains"`` on a non-face variable, or a
            variable located on edges (unsupported).
    """
    var, arr = self._element_values(variable_name, time_index=time_index)
    xs = np.atleast_1d(np.asarray(x, dtype="float64"))
    ys = np.atleast_1d(np.asarray(y, dtype="float64"))
    index = MeshSpatialIndex(self._mesh)
    if var.location == "face":
        if method == "contains":
            idx = index.locate_faces(xs, ys)
        elif method == "nearest":
            idx = np.atleast_1d(index.locate_nearest_face(xs, ys)).ravel()
        else:
            raise ValueError(
                f"sample method must be 'contains' or 'nearest', got {method!r}"
            )
    elif var.location == "node":
        # A node is a point, so "contains" has no meaning here — only "nearest"
        # applies. Reject "contains" rather than silently doing a nearest lookup, as
        # the docstring promises.
        if method == "contains":
            raise ValueError(
                "sample method='contains' is only valid for a face-located variable; "
                f"{variable_name!r} is on 'node' — use method='nearest'."
            )
        if method != "nearest":
            raise ValueError(
                f"sample method must be 'contains' or 'nearest', got {method!r}"
            )
        idx = np.atleast_1d(index.locate_nearest_node(xs, ys)).ravel()
    else:
        raise ValueError(
            f"sample supports 'face' and 'node' variables; {variable_name!r} is on "
            f"{var.location!r}."
        )
    out = np.full(len(xs), np.nan, dtype="float64")
    inside = idx >= 0
    out[inside] = arr[idx[inside]]
    return out

weighted(variable_name, *, how='mean', time_index=0, q=None) #

Area-weighted statistic of a face variable over the mesh.

An irregular mesh has faces of different sizes, so the meaningful aggregate weights each face by its area. Delegates to the shared :func:pyramids.base._reductions.weighted_statistic with :attr:Mesh2d.face_areas as the weights — the same kernel the raster weighted reduction uses.

Parameters:

Name Type Description Default
variable_name str

Name of a face-located data variable.

required
how str

One of "mean", "sum", "sum_of_weights", "std", "var", "quantile" (which needs q). Defaults to "mean".

'mean'
time_index int

Step for a temporal variable. Defaults to 0.

0
q float | None

The quantile in [0, 1] when how="quantile" (the area-weighted quantile uses the Hazen convention and does not match reduce(how="quantile")); must be None otherwise.

None

Returns:

Name Type Description
float float

The area-weighted statistic over all faces.

Raises:

Type Description
ValueError

how is not one of WEIGHTED_HOWS; the variable is not face-located; or its length does not match the number of faces.

Examples:

  • Area-weighted mean: the larger face (area 4, value 10) outweighs the smaller (area 2, value 20), pulling the mean below the unweighted 15.0:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 4.0, 4.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 2.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"v": np.array([10.0, 20.0])},
    ... )
    >>> round(mesh.weighted("v"), 3)
    13.333
    
  • The area-weighted quantile clamps to the data range at the extremes:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 4.0, 4.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 2.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"v": np.array([10.0, 20.0])},
    ... )
    >>> mesh.weighted("v", how="quantile", q=0.0)
    10.0
    >>> mesh.weighted("v", how="quantile", q=1.0)
    20.0
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def weighted(
    self,
    variable_name: str,
    *,
    how: str = "mean",
    time_index: int = 0,
    q: float | None = None,
) -> float:
    """Area-weighted statistic of a face variable over the mesh.

    An irregular mesh has faces of different sizes, so the meaningful aggregate weights
    each face by its area. Delegates to the shared
    :func:`pyramids.base._reductions.weighted_statistic` with :attr:`Mesh2d.face_areas`
    as the weights — the same kernel the raster ``weighted`` reduction uses.

    Args:
        variable_name: Name of a **face-located** data variable.
        how: One of ``"mean"``, ``"sum"``, ``"sum_of_weights"``, ``"std"``, ``"var"``,
            ``"quantile"`` (which needs ``q``). Defaults to ``"mean"``.
        time_index: Step for a temporal variable. Defaults to 0.
        q: The quantile in ``[0, 1]`` when ``how="quantile"`` (the area-weighted quantile
            uses the Hazen convention and does not match ``reduce(how="quantile")``); must be
            ``None`` otherwise.

    Returns:
        float: The area-weighted statistic over all faces.

    Raises:
        ValueError: ``how`` is not one of ``WEIGHTED_HOWS``; the variable is not
            face-located; or its length does not match the number of faces.

    Examples:
        - Area-weighted mean: the larger face (area 4, value 10) outweighs the
          smaller (area 2, value 20), pulling the mean below the unweighted 15.0:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 4.0, 4.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 2.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"v": np.array([10.0, 20.0])},
            ... )
            >>> round(mesh.weighted("v"), 3)
            13.333

            ```
        - The area-weighted quantile clamps to the data range at the extremes:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 4.0, 4.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 2.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"v": np.array([10.0, 20.0])},
            ... )
            >>> mesh.weighted("v", how="quantile", q=0.0)
            10.0
            >>> mesh.weighted("v", how="quantile", q=1.0)
            20.0

            ```
    """
    if how not in WEIGHTED_HOWS:
        # Validate up front, mirroring the raster weighted path: the kernel's catch-all
        # else-branch would otherwise return the standard deviation for any unsupported
        # `how`, a silent wrong answer.
        raise ValueError(
            f"weighted: how must be one of {sorted(WEIGHTED_HOWS)}, got {how!r}."
        )
    if how == "quantile":
        if q is None or isinstance(q, bool) or not 0.0 <= float(q) <= 1.0:
            raise ValueError(
                f"weighted(how='quantile') needs q in [0, 1], got {q!r}."
            )
    elif q is not None:
        raise ValueError(
            f"weighted(q=...) is only valid with how='quantile', not {how!r}."
        )
    var, arr = self._element_values(variable_name, time_index=time_index)
    if var.location != "face":
        raise ValueError(
            "area-weighted statistics need a face-located variable; "
            f"{variable_name!r} is on {var.location!r}."
        )
    areas = self._mesh.face_areas
    if arr.shape[-1] != areas.shape[0]:
        raise ValueError(
            f"variable {variable_name!r} has {arr.shape[-1]} face value(s) but the "
            f"mesh has {areas.shape[0]} face(s)."
        )
    # `arr` already carries NaN for gaps, so `ndv=None` and `skipna=True` reduce over
    # the single face axis; the kernel keeps the axis as length 1, squeezed off here.
    result = weighted_statistic(arr, areas, (0,), how, None, True, q)
    return float(np.asarray(result).ravel()[0])

zonal_stats(zones, *, variable_name, stats=('mean',), weighted=True, time_index=0) #

Aggregate a face variable within polygons, weighted by face area.

The mesh counterpart of :func:pyramids.dataset.ops._zonal.zonal_stats. Each face is assigned to the zone whose polygon contains its centroid (the mesh analogue of a raster pixel's cell centre), then the shared :func:pyramids.base._reductions.reduce_by_label reduces the face values per zone. With weighted (the default) the averaging statistics (mean / std / var) are area-weighted, so a zone's mean is area-exact — a capability the raster path does not yet have. sum is always the plain Σ value (never an area integral), and count / min / max are weight-invariant.

Parameters:

Name Type Description Default
zones Any

Polygons, as a :class:~pyramids.feature.FeatureCollection (or any object exposing geometry, index and len). CRS must match the mesh; reproject first if not.

required
variable_name str

Name of a face-located data variable.

required
stats tuple[str, ...]

Statistics per zone, any of "mean", "sum", "min", "max", "std", "var", "count". Defaults to ("mean",).

('mean',)
weighted bool

Area-weight the averaging statistics (mean / std / var). Defaults to True. sum / count / min / max are unaffected.

True
time_index int

Step for a temporal variable. Defaults to 0.

0

Returns:

Type Description
DataFrame

pandas.DataFrame: Indexed like zones; one column per statistic. A zone

DataFrame

containing no face centroid is NaN (count 0.0).

Raises:

Type Description
ValueError

The variable is not face-located, or the zones' CRS disagrees with the mesh CRS.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def zonal_stats(
    self,
    zones: Any,
    *,
    variable_name: str,
    stats: tuple[str, ...] = ("mean",),
    weighted: bool = True,
    time_index: int = 0,
) -> pd.DataFrame:
    """Aggregate a face variable within polygons, weighted by face area.

    The mesh counterpart of :func:`pyramids.dataset.ops._zonal.zonal_stats`. Each face
    is assigned to the zone whose polygon contains its centroid (the mesh analogue of a
    raster pixel's cell centre), then the shared
    :func:`pyramids.base._reductions.reduce_by_label` reduces the face values per zone.
    With ``weighted`` (the default) the **averaging** statistics (``mean`` / ``std`` /
    ``var``) are area-weighted, so a zone's mean is area-exact — a capability the raster
    path does not yet have. ``sum`` is always the plain Σ value (never an area integral),
    and ``count`` / ``min`` / ``max`` are weight-invariant.

    Args:
        zones: Polygons, as a :class:`~pyramids.feature.FeatureCollection` (or any
            object exposing ``geometry``, ``index`` and ``len``). CRS must match the
            mesh; reproject first if not.
        variable_name: Name of a **face-located** data variable.
        stats: Statistics per zone, any of ``"mean"``, ``"sum"``, ``"min"``, ``"max"``,
            ``"std"``, ``"var"``, ``"count"``. Defaults to ``("mean",)``.
        weighted: Area-weight the averaging statistics (``mean`` / ``std`` / ``var``).
            Defaults to True. ``sum`` / ``count`` / ``min`` / ``max`` are unaffected.
        time_index: Step for a temporal variable. Defaults to 0.

    Returns:
        pandas.DataFrame: Indexed like ``zones``; one column per statistic. A zone
        containing no face centroid is NaN (``count`` ``0.0``).

    Raises:
        ValueError: The variable is not face-located, or the zones' CRS disagrees with
            the mesh CRS.
    """
    var, arr = self._element_values(variable_name, time_index=time_index)
    if var.location != "face":
        raise ValueError(
            "mesh zonal_stats needs a face-located variable; "
            f"{variable_name!r} is on {var.location!r}."
        )
    zone_crs = getattr(zones, "crs", None)
    if zone_crs is not None and self.epsg is not None:
        zone_epsg = zone_crs.to_epsg()
        if zone_epsg is not None and zone_epsg != self.epsg:
            raise ValueError(
                f"zonal_stats: zones CRS (EPSG:{zone_epsg}) does not match mesh CRS "
                f"(EPSG:{self.epsg}). Reproject the zones to the mesh CRS first."
            )
    geometries = list(zones.geometry)
    cx, cy = self._mesh.face_centroids
    centroids = shapely.points(cx, cy)
    tree = shapely.STRtree(geometries)
    # Face centroid within a zone polygon -> that zone. A centroid in more than one
    # (overlapping zones) keeps the first, mirroring a raster pixel landing in one cell.
    centroid_idx, zone_idx = tree.query(centroids, predicate="within")
    labels = np.full(self._mesh.n_face, -1, dtype=np.intp)
    for face_i, zone_i in zip(centroid_idx, zone_idx):
        if labels[face_i] == -1:
            labels[face_i] = zone_i
    n_zones = len(geometries)
    columns: dict[str, np.typing.NDArray] = {}
    # Area weighting applies only to the averaging statistics. `sum` stays the plain
    # Σ value (a weighted sum would be an area integral — a different quantity, and a
    # silent surprise); `count` / `min` / `max` are weight-invariant anyway.
    averaging = [s for s in stats if s in ("mean", "std", "var")]
    plain = [s for s in stats if s not in ("mean", "std", "var")]
    if weighted and averaging:
        columns.update(
            reduce_by_label(
                arr, labels, n_zones, averaging, weights=self._mesh.face_areas
            )
        )
        if plain:
            columns.update(reduce_by_label(arr, labels, n_zones, plain))
    else:
        columns.update(reduce_by_label(arr, labels, n_zones, list(stats)))
    return pd.DataFrame({stat: columns[stat] for stat in stats}, index=zones.index)

reduce(how, *, skipna=True, q=None, groupby=None) #

Reduce the time dimension of every temporal variable, whole or in groups.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.reduce over time. Each temporal variable is reduced along its time axis through the shared :func:pyramids.base._reductions.reduce_axis — the very kernel the raster reductions use. Non-temporal variables are kept unchanged.

Without groupby the whole axis collapses to one statistic and the variable becomes static. With groupby each group is reduced on its own slab and the results are stacked back along the time axis, so the variable stays temporal with one step per group — the same shape contract the raster grouped reduce has. For a (4, 2) variable over four monthly steps, reduce("mean") answers shape (2,) with has_time False, while reduce("mean", groupby="MS") answers shape (2, 2) with has_time still True.

Parameters:

Name Type Description Default
how str

One of "mean", "sum", "min", "max", "std", "var", "median", "prod", "quantile", "count", "all" or "any".

required
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True
q float | None

The quantile for how="quantile"; must stay None otherwise.

None
groupby Any

Reduce within groups of steps instead of over the whole axis. Two spellings, matching the raster grouped reduce: a sequence of per-step labels the same length as the time axis (grouped in first-appearance order, so the caller controls the order), or a pandas offset alias ("MS", "YS", …) binned against the dataset's date-like time coordinates. Each group's label becomes the result's time_values entry, and empty bins are dropped. None reduces the whole axis. Defaults to None.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset. Without groupby each temporal variable is

UgridDataset

collapsed over time into a static per-element variable; with groupby each one

UgridDataset

keeps its time dimension, at one step per group.

Raises:

Type Description
ValueError

how is not a known reduction; q is given for a non-quantile how or missing for how="quantile"; no variable has a time dimension; a temporal variable has no loaded data; a groupby label sequence's length is not the time length; or a groupby offset alias is asked of time coordinates that are step positions, or that pandas cannot read as dates.

Examples:

  • Mean over two time steps of a per-face variable:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"d": np.array([[1.0, 2.0], [3.0, 4.0]])},
    ...     data_locations={"d": "face"},
    ... )
    >>> mesh["d"].has_time
    True
    >>> reduced = mesh.reduce("mean")
    >>> reduced["d"].data.tolist()
    [2.0, 3.0]
    >>> reduced["d"].has_time
    False
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def reduce(
    self,
    how: str,
    *,
    skipna: bool = True,
    q: float | None = None,
    groupby: Any = None,
) -> UgridDataset:
    """Reduce the time dimension of every temporal variable, whole or in groups.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.reduce` over time. Each
    temporal variable is reduced along its time axis through the shared
    :func:`pyramids.base._reductions.reduce_axis` — the very kernel the raster reductions
    use. Non-temporal variables are kept unchanged.

    Without ``groupby`` the whole axis collapses to one statistic and the variable becomes
    static. With ``groupby`` each group is reduced on its own slab and the results are
    stacked back along the time axis, so the variable stays temporal with one step per
    group — the same shape contract the raster grouped reduce has. For a ``(4, 2)``
    variable over four monthly steps, ``reduce("mean")`` answers shape ``(2,)`` with
    ``has_time`` False, while ``reduce("mean", groupby="MS")`` answers shape ``(2, 2)``
    with ``has_time`` still True.

    Args:
        how: One of ``"mean"``, ``"sum"``, ``"min"``, ``"max"``, ``"std"``, ``"var"``,
            ``"median"``, ``"prod"``, ``"quantile"``, ``"count"``, ``"all"`` or ``"any"``.
        skipna: Skip the declared no-data value and NaN. Defaults to True.
        q: The quantile for ``how="quantile"``; must stay ``None`` otherwise.
        groupby: Reduce within groups of steps instead of over the whole axis. Two
            spellings, matching the raster grouped reduce: a **sequence of per-step
            labels** the same length as the time axis (grouped in first-appearance order,
            so the caller controls the order), or a **pandas offset alias** (``"MS"``,
            ``"YS"``, …) binned against the dataset's date-like time coordinates. Each
            group's label becomes the result's ``time_values`` entry, and empty bins are
            dropped. ``None`` reduces the whole axis. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset. Without ``groupby`` each temporal variable is
        collapsed over time into a static per-element variable; with ``groupby`` each one
        keeps its time dimension, at one step per group.

    Raises:
        ValueError: ``how`` is not a known reduction; ``q`` is given for a non-quantile
            ``how`` or missing for ``how="quantile"``; no variable has a time dimension;
            a temporal variable has no loaded data; a ``groupby`` label sequence's length
            is not the time length; or a ``groupby`` offset alias is asked of time
            coordinates that are step positions, or that pandas cannot read as dates.

    Examples:
        - Mean over two time steps of a per-face variable:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"d": np.array([[1.0, 2.0], [3.0, 4.0]])},
            ...     data_locations={"d": "face"},
            ... )
            >>> mesh["d"].has_time
            True
            >>> reduced = mesh.reduce("mean")
            >>> reduced["d"].data.tolist()
            [2.0, 3.0]
            >>> reduced["d"].has_time
            False

            ```
    """
    _check_reduce_how(how, q)
    self._require_temporal("reduce")
    # all/any collapse to a uint8 flag band whose all-gap value is FLAG_NO_DATA (255);
    # the collapsed variable must declare that so a consumer does not read 255 as data.
    result_nodata = FLAG_NO_DATA if how in ("all", "any") else None
    grouped = (
        _group_positions(self._time_coords("reduce"), groupby)
        if groupby is not None
        else None
    )
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time:
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to reduce.")
        arr = np.asarray(data)
        nodata = result_nodata if result_nodata is not None else var.nodata
        if grouped is None:
            reduced = reduce_axis(arr, axis, how, skipna, var.nodata, q)
            new_vars[name] = _static_from(
                var, np.asarray(reduced), axis, nodata=nodata
            )
            continue
        labels, positions = grouped
        # Each group is reduced on its own slab and the results stacked back along the
        # time axis, so a grouped reduce keeps the dimension (shorter) instead of
        # collapsing it — the same shape contract the raster grouped reduce has.
        parts = [
            np.asarray(
                reduce_axis(
                    np.take(arr, group, axis=axis), axis, how, skipna, var.nodata, q
                )
            )
            for group in positions
        ]
        # A grouped reduce re-bins the time axis, so a per-step mask no longer aligns —
        # even when n_groups == n_time keeps the shape, which would slip past the
        # length-only implicit guard (review L3). Drop it; a static mask is step-
        # independent and kept.
        new_var = var.with_data(
            np.stack(parts, axis=axis),
            active=None if var.active_has_time else _KEEP_ACTIVE,
        )
        new_var.nodata = nodata
        new_var.attributes = {**var.attributes, "time_values": list(labels)}
        new_vars[name] = new_var
    return self._rebuild(new_vars)

resample(freq, how='mean', *, skipna=True, q=None) #

Bin the time axis by a calendar frequency and reduce each bin.

Sugar over reduce(how, groupby=freq): the mesh counterpart of the raster resample. The time coordinates must be date-like, since the bins come from a pandas offset alias ("1MS", "YS", "7D", …). The time dimension is kept, one step per non-empty bin, stamped with pandas' own label for that bin — which is the bin's start for a start-anchored alias and its end for an end-anchored one. Over steps in January, February and March 2020, "MS" labels the bins 01-01 / 02-01 / 03-01 while "ME" labels them 01-31 / 02-29 / 03-31, and "W" labels each week by its Sunday.

Parameters:

Name Type Description Default
freq str

A pandas offset alias naming the bin width.

required
how str

The statistic each bin is reduced with. Defaults to "mean".

'mean'
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True
q float | None

The quantile, required when how="quantile".

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with one time step per bin.

Raises:

Type Description
ValueError

No variable has a time dimension, the coordinates are not date-like, or how/q is invalid.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def resample(
    self,
    freq: str,
    how: str = "mean",
    *,
    skipna: bool = True,
    q: float | None = None,
) -> UgridDataset:
    """Bin the time axis by a calendar frequency and reduce each bin.

    Sugar over ``reduce(how, groupby=freq)``: the mesh counterpart of the raster
    ``resample``. The time coordinates must be date-like, since the bins come from a pandas
    offset alias (``"1MS"``, ``"YS"``, ``"7D"``, …). The time dimension is kept, one step
    per non-empty bin, stamped with **pandas' own label for that bin** — which is the bin's
    start for a start-anchored alias and its end for an end-anchored one. Over steps in
    January, February and March 2020, ``"MS"`` labels the bins 01-01 / 02-01 / 03-01 while
    ``"ME"`` labels them 01-31 / 02-29 / 03-31, and ``"W"`` labels each week by its Sunday.

    Args:
        freq: A pandas offset alias naming the bin width.
        how: The statistic each bin is reduced with. Defaults to ``"mean"``.
        skipna: Skip the declared no-data value and NaN. Defaults to True.
        q: The quantile, required when ``how="quantile"``.

    Returns:
        UgridDataset: A new dataset with one time step per bin.

    Raises:
        ValueError: No variable has a time dimension, the coordinates are not date-like,
            or ``how``/``q`` is invalid.
    """
    return self.reduce(how, skipna=skipna, q=q, groupby=freq)

mean(*, skipna=True) #

Mean over time of every temporal variable (thin wrapper over :meth:reduce).

Parameters:

Name Type Description Default
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset; each temporal variable collapsed to its time mean.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def mean(self, *, skipna: bool = True) -> UgridDataset:
    """Mean over time of every temporal variable (thin wrapper over :meth:`reduce`).

    Args:
        skipna: Skip the declared no-data value and NaN. Defaults to True.

    Returns:
        UgridDataset: A new dataset; each temporal variable collapsed to its time mean.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self.reduce("mean", skipna=skipna)

sum(*, skipna=True) #

Sum over time of every temporal variable (thin wrapper over :meth:reduce).

Parameters:

Name Type Description Default
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset; each temporal variable collapsed to its time sum.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sum(self, *, skipna: bool = True) -> UgridDataset:
    """Sum over time of every temporal variable (thin wrapper over :meth:`reduce`).

    Args:
        skipna: Skip the declared no-data value and NaN. Defaults to True.

    Returns:
        UgridDataset: A new dataset; each temporal variable collapsed to its time sum.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self.reduce("sum", skipna=skipna)

min(*, skipna=True) #

Minimum over time of every temporal variable (thin wrapper over :meth:reduce).

Parameters:

Name Type Description Default
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset; each temporal variable collapsed to its time minimum.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def min(self, *, skipna: bool = True) -> UgridDataset:
    """Minimum over time of every temporal variable (thin wrapper over :meth:`reduce`).

    Args:
        skipna: Skip the declared no-data value and NaN. Defaults to True.

    Returns:
        UgridDataset: A new dataset; each temporal variable collapsed to its time minimum.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self.reduce("min", skipna=skipna)

max(*, skipna=True) #

Maximum over time of every temporal variable (thin wrapper over :meth:reduce).

Parameters:

Name Type Description Default
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset; each temporal variable collapsed to its time maximum.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def max(self, *, skipna: bool = True) -> UgridDataset:
    """Maximum over time of every temporal variable (thin wrapper over :meth:`reduce`).

    Args:
        skipna: Skip the declared no-data value and NaN. Defaults to True.

    Returns:
        UgridDataset: A new dataset; each temporal variable collapsed to its time maximum.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self.reduce("max", skipna=skipna)

std(*, skipna=True) #

Std-dev over time of every temporal variable (thin wrapper over :meth:reduce).

Parameters:

Name Type Description Default
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset; each temporal variable collapsed to its time std.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def std(self, *, skipna: bool = True) -> UgridDataset:
    """Std-dev over time of every temporal variable (thin wrapper over :meth:`reduce`).

    Args:
        skipna: Skip the declared no-data value and NaN. Defaults to True.

    Returns:
        UgridDataset: A new dataset; each temporal variable collapsed to its time std.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self.reduce("std", skipna=skipna)

var(*, skipna=True) #

Variance over time of every temporal variable (thin wrapper over :meth:reduce).

Parameters:

Name Type Description Default
skipna bool

Skip the declared no-data value and NaN. Defaults to True.

True

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset; each temporal variable collapsed to its time variance.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def var(self, *, skipna: bool = True) -> UgridDataset:
    """Variance over time of every temporal variable (thin wrapper over :meth:`reduce`).

    Args:
        skipna: Skip the declared no-data value and NaN. Defaults to True.

    Returns:
        UgridDataset: A new dataset; each temporal variable collapsed to its time variance.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self.reduce("var", skipna=skipna)

cumsum() #

Cumulative sum along time for every temporal variable.

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset in which each temporal variable holds the running

UgridDataset

sum of its steps along the time axis; static variables are unchanged.

Raises:

Type Description
ValueError

No variable has a time dimension, or a temporal variable has no loaded data.

Examples:

  • Running sum over three time steps of a per-face variable:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"d": np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])},
    ...     data_locations={"d": "face"},
    ... )
    >>> mesh.cumsum()["d"].data.tolist()
    [[1.0, 2.0], [4.0, 6.0], [9.0, 12.0]]
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def cumsum(self) -> UgridDataset:
    """Cumulative sum along time for every temporal variable.

    Returns:
        UgridDataset: A new dataset in which each temporal variable holds the running
        sum of its steps along the time axis; static variables are unchanged.

    Raises:
        ValueError: No variable has a time dimension, or a temporal variable has no
            loaded data.

    Examples:
        - Running sum over three time steps of a per-face variable:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"d": np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])},
            ...     data_locations={"d": "face"},
            ... )
            >>> mesh.cumsum()["d"].data.tolist()
            [[1.0, 2.0], [4.0, 6.0], [9.0, 12.0]]

            ```
    """
    return self._transform_time("cumsum", lambda d, axis: np.cumsum(d, axis=axis))

cumprod() #

Cumulative product along time for every temporal variable.

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset in which each temporal variable holds the running

UgridDataset

product of its steps along the time axis; static variables are unchanged.

Raises:

Type Description
ValueError

No variable has a time dimension, or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def cumprod(self) -> UgridDataset:
    """Cumulative product along time for every temporal variable.

    Returns:
        UgridDataset: A new dataset in which each temporal variable holds the running
        product of its steps along the time axis; static variables are unchanged.

    Raises:
        ValueError: No variable has a time dimension, or a temporal variable has no
            loaded data.
    """
    return self._transform_time("cumprod", lambda d, axis: np.cumprod(d, axis=axis))

shift(periods=1) #

Shift each temporal variable periods steps along time, vacated steps NaN.

Parameters:

Name Type Description Default
periods int

Steps to shift; negative shifts towards the start. Defaults to 1.

1

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with each temporal variable shifted along time, the

UgridDataset

vacated steps filled with NaN; static variables are unchanged.

Raises:

Type Description
ValueError

No variable has a time dimension, or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def shift(self, periods: int = 1) -> UgridDataset:
    """Shift each temporal variable ``periods`` steps along time, vacated steps NaN.

    Args:
        periods: Steps to shift; negative shifts towards the start. Defaults to 1.

    Returns:
        UgridDataset: A new dataset with each temporal variable shifted along time, the
        vacated steps filled with NaN; static variables are unchanged.

    Raises:
        ValueError: No variable has a time dimension, or a temporal variable has no
            loaded data.
    """
    return self._transform_time(
        "shift",
        lambda d, axis: shifted(d, axis, periods, np.nan),
        # Move a per-step mask with the snapshots (time on axis 0), vacated steps inactive —
        # a shifted-in step holds NaN data, so False is right (review H1).
        active_fn=lambda m: shifted(m, 0, periods, False),
    )

polyfit(deg, variable_name=None) #

Fit a polynomial per element along time, returning its coefficients (#1377).

The mesh counterpart of the raster polyfit, and what produces a trend map: a degree-1 fit per face gives the slope of that face's series.

The time axis is replaced by a coefficient axis of length deg + 1, highest power first — the order :func:numpy.polyfit returns. The result is therefore no longer a time series, so it is marked static.

Parameters:

Name Type Description Default
deg int

Polynomial degree.

required
variable_name str | None

Variable to fit (default: every temporal variable).

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose variables carry the fitted coefficients.

Raises:

Type Description
ValueError

No variable has a time dimension, deg is negative, or the axis is too short for the degree.

See Also

curvefit: Fit an arbitrary model instead of a polynomial. differentiate: The instantaneous rate rather than a fitted trend.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def polyfit(self, deg: int, variable_name: str | None = None) -> UgridDataset:
    """Fit a polynomial per element along time, returning its coefficients (#1377).

    The mesh counterpart of the raster ``polyfit``, and what produces a **trend map**: a
    degree-1 fit per face gives the slope of that face's series.

    The time axis is replaced by a ``coefficient`` axis of length ``deg + 1``, highest
    power first — the order :func:`numpy.polyfit` returns. The result is therefore no
    longer a time series, so it is marked static.

    Args:
        deg: Polynomial degree.
        variable_name: Variable to fit (default: every temporal variable).

    Returns:
        UgridDataset: A new dataset whose variables carry the fitted coefficients.

    Raises:
        ValueError: No variable has a time dimension, ``deg`` is negative, or the axis is
            too short for the degree.

    See Also:
        curvefit: Fit an arbitrary model instead of a polynomial.
        differentiate: The instantaneous rate rather than a fitted trend.
    """
    self._require_variable_name("polyfit", variable_name)
    self._alongtime_coord("polyfit")
    return self._fit_alongtime(
        variable_name,
        lambda values, axis, nodata, coord: _timeseries.polyfit_axis(
            values, coord, deg, axis, nodata
        ),
        "coefficient",
    )

curvefit(func, p0=None, variable_name=None) #

Fit an arbitrary model per element along time (#1377).

The general form of :meth:polyfit. Each element is fitted in turn, since there is no closed form; an element whose fit does not converge yields NaN parameters rather than failing the whole call, so one bad face does not lose the other thousands.

Parameters:

Name Type Description Default
func Any

The model f(x, *params). x is the time coordinate as seconds elapsed from the first stamp when the axis carries datetimes.

required
p0 Any

Initial parameter guess. Without one the parameter count is read from func's signature.

None
variable_name str | None

Variable to fit (default: every temporal variable).

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose variables carry the fitted parameters along a

UgridDataset

parameter axis.

Raises:

Type Description
ValueError

No variable has a time dimension.

See Also

polyfit: The closed-form polynomial case, much faster.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def curvefit(
    self, func: Any, p0: Any = None, variable_name: str | None = None
) -> UgridDataset:
    """Fit an arbitrary model per element along time (#1377).

    The general form of :meth:`polyfit`. Each element is fitted in turn, since there is no
    closed form; an element whose fit does not converge yields ``NaN`` parameters rather
    than failing the whole call, so one bad face does not lose the other thousands.

    Args:
        func: The model ``f(x, *params)``. ``x`` is the time coordinate as seconds elapsed
            from the first stamp when the axis carries datetimes.
        p0: Initial parameter guess. Without one the parameter count is read from ``func``'s
            signature.
        variable_name: Variable to fit (default: every temporal variable).

    Returns:
        UgridDataset: A new dataset whose variables carry the fitted parameters along a
        ``parameter`` axis.

    Raises:
        ValueError: No variable has a time dimension.

    See Also:
        polyfit: The closed-form polynomial case, much faster.
    """
    self._require_variable_name("curvefit", variable_name)
    self._alongtime_coord("curvefit")
    return self._fit_alongtime(
        variable_name,
        lambda values, axis, nodata, coord: _timeseries.curvefit_axis(
            values, coord, func, p0, axis, nodata
        ),
        "parameter",
    )

differentiate(variable_name=None) #

The derivative of every temporal variable along time (#1377).

Honours the time coordinate's own spacing, so an unevenly spaced output interval gives the right rate rather than one assuming a uniform step. With a decoded datetime axis (issue #1381) the result is per second.

Parameters:

Name Type Description Default
variable_name str | None

Variable to differentiate (default: every temporal variable).

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset of rates, the same shape as the input.

Raises:

Type Description
ValueError

No variable has a time dimension, or the axis has fewer than two steps.

See Also

integrate: The inverse operation, which consumes the axis.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def differentiate(self, variable_name: str | None = None) -> UgridDataset:
    """The derivative of every temporal variable along time (#1377).

    Honours the time coordinate's own spacing, so an unevenly spaced output interval gives
    the right rate rather than one assuming a uniform step. With a decoded datetime axis
    (issue #1381) the result is **per second**.

    Args:
        variable_name: Variable to differentiate (default: every temporal variable).

    Returns:
        UgridDataset: A new dataset of rates, the same shape as the input.

    Raises:
        ValueError: No variable has a time dimension, or the axis has fewer than two steps.

    See Also:
        integrate: The inverse operation, which consumes the axis.
    """
    self._require_variable_name("differentiate", variable_name)
    self._alongtime_coord("differentiate")
    return self._map_alongtime(
        "differentiate",
        variable_name,
        lambda values, axis, _nodata, coord: _timeseries.differentiate_axis(
            values, coord, axis
        ),
    )

cumulative_integrate(variable_name=None) #

The running integral of every temporal variable along time (#1377).

Keeps the time axis, unlike :meth:integrate. The first step is 0 — nothing has accumulated yet.

Parameters:

Name Type Description Default
variable_name str | None

Variable to integrate (default: every temporal variable).

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset of running integrals, the same shape as the input.

Raises:

Type Description
ValueError

No variable has a time dimension, or the axis has fewer than two steps.

See Also

integrate: The definite integral, which consumes the axis.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def cumulative_integrate(self, variable_name: str | None = None) -> UgridDataset:
    """The running integral of every temporal variable along time (#1377).

    Keeps the time axis, unlike :meth:`integrate`. The first step is ``0`` — nothing has
    accumulated yet.

    Args:
        variable_name: Variable to integrate (default: every temporal variable).

    Returns:
        UgridDataset: A new dataset of running integrals, the same shape as the input.

    Raises:
        ValueError: No variable has a time dimension, or the axis has fewer than two steps.

    See Also:
        integrate: The definite integral, which consumes the axis.
    """
    self._require_variable_name("cumulative_integrate", variable_name)
    self._alongtime_coord("cumulative_integrate")
    return self._map_alongtime(
        "cumulative_integrate",
        variable_name,
        lambda values, axis, _nodata, coord: _timeseries.cumulative_integrate_axis(
            values, coord, axis
        ),
    )

rank(variable_name=None, *, pct=False) #

Rank each element's values along time, ties averaged (#1377).

Per face this is an exceedance map: where does each step sit among all the steps at that face. Needs no date coordinate, so it works on a positional axis too.

The declared sentinel and NaN are excluded rather than ranked, as the cube's rank excludes them — ranking a -9999 as the smallest value would shift every real rank by one.

Parameters:

Name Type Description Default
variable_name str | None

Variable to rank (default: every temporal variable).

None
pct bool

Report each rank as a fraction of that element's usable values rather than a count, so its largest usable value is 1.0.

False

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset of ranks, the same shape as the input, counting from 1

UgridDataset

(or in (0, 1] with pct=True), with NaN where the value was missing.

Raises:

Type Description
ValueError

No variable has a time dimension.

See Also

idxmax: The step at which each element peaks.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def rank(
    self, variable_name: str | None = None, *, pct: bool = False
) -> UgridDataset:
    """Rank each element's values along time, ties averaged (#1377).

    Per face this is an **exceedance map**: where does each step sit among all the steps at
    that face. Needs no date coordinate, so it works on a positional axis too.

    The declared sentinel and ``NaN`` are excluded rather than ranked, as the cube's
    ``rank`` excludes them — ranking a ``-9999`` as the smallest value would shift every
    real rank by one.

    Args:
        variable_name: Variable to rank (default: every temporal variable).
        pct: Report each rank as a fraction of that element's usable values rather than a
            count, so its largest usable value is ``1.0``.

    Returns:
        UgridDataset: A new dataset of ranks, the same shape as the input, counting from 1
        (or in ``(0, 1]`` with ``pct=True``), with ``NaN`` where the value was missing.

    Raises:
        ValueError: No variable has a time dimension.

    See Also:
        idxmax: The step at which each element peaks.
    """
    self._require_variable_name("rank", variable_name)
    self._require_temporal("rank")
    return self._map_alongtime(
        "rank",
        variable_name,
        lambda values, axis, nodata, _coord: _timeseries.rank_axis(
            values, axis, nodata, pct
        ),
    )

integrate(variable_name=None) #

The definite integral of every temporal variable along time (#1377).

The integral consumes the time axis, so the result is static — one value per element, as :meth:reduce produces. With a decoded datetime axis the units are value-seconds.

Parameters:

Name Type Description Default
variable_name str | None

Variable to integrate (default: every temporal variable).

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose temporal variables are now static totals.

Raises:

Type Description
ValueError

No variable has a time dimension, or the axis has fewer than two steps.

See Also

cumulative_integrate: The running integral, which keeps the axis. differentiate: The inverse operation.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def integrate(self, variable_name: str | None = None) -> UgridDataset:
    """The definite integral of every temporal variable along time (#1377).

    The integral **consumes** the time axis, so the result is static — one value per
    element, as :meth:`reduce` produces. With a decoded datetime axis the units are
    value-seconds.

    Args:
        variable_name: Variable to integrate (default: every temporal variable).

    Returns:
        UgridDataset: A new dataset whose temporal variables are now static totals.

    Raises:
        ValueError: No variable has a time dimension, or the axis has fewer than two steps.

    See Also:
        cumulative_integrate: The running integral, which keeps the axis.
        differentiate: The inverse operation.
    """
    self._require_variable_name("integrate", variable_name)
    self._alongtime_coord("integrate")
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time or (
            variable_name is not None and name != variable_name
        ):
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to integrate.")
        total = _timeseries.integrate_axis(
            np.asarray(data), _variable_time_coord(var), axis
        )
        # The implicit carry is what decides: a static mask survives the collapse (as it
        # does through `reduce`), while a per-step one cannot follow an axis that is gone.
        # Passing `active=None` here force-dropped both.
        collapsed = _static_from(var, total, axis)
        collapsed.attributes = _without_time_metadata(collapsed.attributes)
        # The total is in value-seconds, not the input's units, so the input's sentinel
        # does not describe it.
        collapsed.nodata = None
        new_vars[name] = collapsed
    return self._rebuild(new_vars)

coarsen(window, how='mean', variable_name=None) #

Block-aggregate the time axis into windows of window steps (#1377).

Not a duplicate of :meth:resample. That one bins by a calendar frequency and so needs date-like coordinates; this bins by a count of steps and needs no coordinate at all, which makes it the only option for a mesh whose file carries no CF time units. Where both work, resample is the calendar-aware choice and this the positional one.

A trailing remainder shorter than a full window is dropped, so every reported bin is a full one rather than a short bin that would read as a dip in the series.

A variable with fewer steps than one window cannot be binned at all. In a sweep (variable_name=None) it is passed through untouched, so one short variable does not lose the whole call — the choice :meth:convert_units makes for a variable with no units. Naming such a variable explicitly raises, since that is a request rather than a sweep, and so does a sweep in which no variable could be binned: that call did nothing, and returning the dataset unchanged would look like success.

Parameters:

Name Type Description Default
window int

Steps per block, at least 1.

required
how str

"mean" (default), "sum", "min", "max", "median" or "std".

'mean'
variable_name str | None

Variable to aggregate (default: every temporal variable).

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose time axis holds one step per full block, stamped

UgridDataset

with each block's first coordinate value.

Raises:

Type Description
ValueError

No variable has a time dimension, window is below 1, how is unknown, or the axis is shorter than one window.

See Also

resample: Calendar-frequency binning, when the axis carries real dates. reduce: Collapse the whole axis instead of binning it.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def coarsen(
    self, window: int, how: str = "mean", variable_name: str | None = None
) -> UgridDataset:
    """Block-aggregate the time axis into windows of ``window`` steps (#1377).

    **Not** a duplicate of :meth:`resample`. That one bins by a calendar frequency and so
    needs date-like coordinates; this bins by a **count of steps** and needs no coordinate
    at all, which makes it the only option for a mesh whose file carries no CF time units.
    Where both work, ``resample`` is the calendar-aware choice and this the positional one.

    A trailing remainder shorter than a full window is dropped, so every reported bin is a
    full one rather than a short bin that would read as a dip in the series.

    A variable with fewer steps than one window cannot be binned at all. In a sweep
    (``variable_name=None``) it is passed through untouched, so one short variable does not
    lose the whole call — the choice :meth:`convert_units` makes for a variable with no
    units. Naming such a variable explicitly raises, since that is a request rather than a
    sweep, and so does a sweep in which **no** variable could be binned: that call did
    nothing, and returning the dataset unchanged would look like success.

    Args:
        window: Steps per block, at least 1.
        how: ``"mean"`` (default), ``"sum"``, ``"min"``, ``"max"``, ``"median"`` or
            ``"std"``.
        variable_name: Variable to aggregate (default: every temporal variable).

    Returns:
        UgridDataset: A new dataset whose time axis holds one step per full block, stamped
        with each block's first coordinate value.

    Raises:
        ValueError: No variable has a time dimension, ``window`` is below 1, ``how`` is
            unknown, or the axis is shorter than one window.

    See Also:
        resample: Calendar-frequency binning, when the axis carries real dates.
        reduce: Collapse the whole axis instead of binning it.
    """
    if window < 1:
        raise ValueError(f"coarsen: window must be at least 1, got {window}.")
    self._require_variable_name("coarsen", variable_name)
    self._alongtime_coord("coarsen")
    sweeping = variable_name is None
    new_vars: dict[str, MeshVariable] = {}
    skipped: list[str] = []
    for name, var in self._data_variables.items():
        if not var.has_time or (not sweeping and name != variable_name):
            new_vars[name] = var
            continue
        binned = _coarsened_variable(name, var, window, how, sweeping)
        if binned is None:
            skipped.append(f"{name!r}({var.n_time_steps})")
            new_vars[name] = var
            continue
        new_vars[name] = binned
    if sweeping and len(skipped) == len(
        [v for v in self._data_variables.values() if v.has_time]
    ):
        raise ValueError(
            f"coarsen: no variable has as many as {window} step(s) "
            f"({', '.join(skipped)}), so a window of {window} would report nothing at "
            f"all. Use a smaller window."
        )
    return self._rebuild(new_vars)

interp_like(other) #

Interpolate onto another dataset's time stamps (#1377).

What lines two runs up on a common axis before :meth:concat or an operator. Linear, and deliberately not extrapolating: a target stamp outside this dataset's span comes back as a gap (NaN), which is the contract the raster interp already has.

Parameters:

Name Type Description Default
other UgridDataset

The dataset whose time coordinate supplies the target stamps. Must sit on the same topology.

required
Note

Two dated axes are put on a common decimal-year scale, which means the same thing in every calendar, so this works across calendars as well as within one. The result declares other's units and calendar, since those are the stamps it now carries; an undated other leaves the result positional, with no CF metadata at all.

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset on other's time stamps, carrying other's time

UgridDataset

units and calendar (or none, when other is positional).

Raises:

Type Description
AlignmentError

other sits on a different mesh.

ValueError

Either side has no time dimension; this one has fewer than two steps to interpolate between; or one side is dated and the other positional, which have no common scale.

See Also

interp_time: Interpolate onto a given number of evenly spaced steps.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def interp_like(self, other: UgridDataset) -> UgridDataset:
    """Interpolate onto another dataset's time stamps (#1377).

    What lines two runs up on a common axis before :meth:`concat` or an operator. Linear,
    and deliberately **not** extrapolating: a target stamp outside this dataset's span comes
    back as a gap (NaN), which is the contract the raster ``interp`` already has.

    Args:
        other: The dataset whose time coordinate supplies the target stamps. Must sit on
            the same topology.

    Note:
        Two dated axes are put on a common **decimal-year** scale, which means the same
        thing in every calendar, so this works across calendars as well as within one. The
        result declares ``other``'s units and calendar, since those are the stamps it now
        carries; an undated ``other`` leaves the result positional, with no CF metadata at
        all.

    Returns:
        UgridDataset: A new dataset on ``other``'s time stamps, carrying ``other``'s time
        units and calendar (or none, when ``other`` is positional).

    Raises:
        AlignmentError: ``other`` sits on a different mesh.
        ValueError: Either side has no time dimension; this one has fewer than two steps to
            interpolate between; or one side is dated and the other positional, which have
            no common scale.

    See Also:
        interp_time: Interpolate onto a given number of evenly spaced steps.
    """
    self._assert_same_topology(other, "interp_like")
    self._alongtime_coord("interp_like")
    target = other._alongtime_coord("interp_like")
    target_units, target_calendar = other._declared_time_metadata()
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time:
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(
                f"Variable {name!r} has no loaded data to interpolate."
            )
        source_scale, target_scale = _interp_scale(
            _variable_time_coord(var), target
        )
        moved = var.with_data(
            _timeseries.interp_axis(
                np.asarray(data), source_scale, target_scale, axis
            ),
            # A static mask describes the elements, not the steps, so re-stamping the time
            # axis leaves it valid; only a per-step mask cannot follow. This is the same
            # carry `integrate` and `coarsen` use.
            active=None if var.active_has_time else _KEEP_ACTIVE,
        )
        attributes = {**var.attributes, "time_values": list(target)}
        if target_units is None:
            # The target is positional, so the result's stamps are positions too. Leaving
            # the source's CF units behind would have them re-encoded as real dates that
            # were never in either dataset.
            attributes.pop(TIME_UNITS_ATTR, None)
            attributes.pop(TIME_CALENDAR_ATTR, None)
        else:
            attributes[TIME_UNITS_ATTR] = target_units
            attributes[TIME_CALENDAR_ATTR] = target_calendar
        moved.attributes = attributes
        new_vars[name] = moved
    return self._rebuild(new_vars)

convert_calendar(calendar, *, align_on='date') #

Restamp the time axis onto another CF calendar (issue #1381).

The mesh counterpart of :meth:NetCDF.convert_calendar, and what lets a mesh run on a model calendar be compared or :meth:concat-enated with one on another.

Only the time coordinate changes. No value is touched and nothing is interpolated: each step keeps its values and is given the stamp its date has in the target calendar. A date the target has no day for is dropped, and its step with it — 29 February moving to noleap, 31 December moving to 360_day — so the axis gets shorter. :meth:interp_calendar is the lossless counterpart.

Parameters:

Name Type Description Default
calendar str

The target CF calendar — "standard" / "gregorian", "proleptic_gregorian", "noleap" / "365_day", "all_leap" / "366_day", "360_day" or "julian".

required
align_on str

"date" (default) keeps the calendar date and drops what the target lacks. "year" keeps the position in the year instead, which is what a 360_day axis of model bookkeeping wants; it loses less, but is not lossless either — when the target year is shorter two source days can land on one target day, and the duplicates are dropped to keep the axis strictly monotonic.

'date'

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset whose time axis is restamped onto calendar, carrying

UgridDataset

that calendar and the original units.

Raises:

Type Description
ValueError

The axis carries no CF time units; calendar is not one cftime knows; align_on is neither "date" nor "year"; or every step would be dropped, which would leave nothing to return.

See Also

interp_calendar: Keeps every step by interpolating instead of dropping.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def convert_calendar(
    self, calendar: str, *, align_on: str = "date"
) -> UgridDataset:
    """Restamp the time axis onto another CF calendar (issue #1381).

    The mesh counterpart of :meth:`NetCDF.convert_calendar`, and what lets a mesh run on a
    model calendar be compared or :meth:`concat`-enated with one on another.

    **Only the time coordinate changes.** No value is touched and nothing is interpolated:
    each step keeps its values and is given the stamp its date has in the target calendar.
    A date the target has no day for is **dropped, and its step with it** — 29 February
    moving to ``noleap``, 31 December moving to ``360_day`` — so the axis gets shorter.
    :meth:`interp_calendar` is the lossless counterpart.

    Args:
        calendar: The target CF calendar — ``"standard"`` / ``"gregorian"``,
            ``"proleptic_gregorian"``, ``"noleap"`` / ``"365_day"``, ``"all_leap"`` /
            ``"366_day"``, ``"360_day"`` or ``"julian"``.
        align_on: ``"date"`` (default) keeps the calendar date and drops what the target
            lacks. ``"year"`` keeps the *position in the year* instead, which is what a
            ``360_day`` axis of model bookkeeping wants; it loses less, but is not lossless
            either — when the target year is shorter two source days can land on one target
            day, and the duplicates are dropped to keep the axis strictly monotonic.

    Returns:
        UgridDataset: A new dataset whose time axis is restamped onto ``calendar``, carrying
        that calendar and the original units.

    Raises:
        ValueError: The axis carries no CF time units; ``calendar`` is not one ``cftime``
            knows; ``align_on`` is neither ``"date"`` nor ``"year"``; or every step would be
            dropped, which would leave nothing to return.

    See Also:
        interp_calendar: Keeps every step by interpolating instead of dropping.
    """
    if align_on not in _CALENDAR_ALIGNMENTS:
        raise ValueError(
            f"convert_calendar() got align_on={align_on!r}; it must be one of "
            f"{list(_CALENDAR_ALIGNMENTS)}."
        )
    try:
        cftime.datetime(2001, 1, 1, calendar=calendar)
    except (ValueError, KeyError) as error:
        raise ValueError(
            f"convert_calendar() got calendar={calendar!r}, which cftime does not know: "
            f"{error}"
        ) from error
    instants, units, _source = self._calendar_instants("convert_calendar")
    carried, kept = _carried_to_calendar(instants, calendar, align_on)
    if not kept:
        raise ValueError(
            f"convert_calendar() would drop every step: no date on this axis exists in the "
            f"{calendar!r} calendar."
        )
    indices = np.asarray(kept, dtype=np.intp)
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time:
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to restamp.")
        active = var.active
        if active is not None and var.active_has_time:
            # The mask is per step, so it loses exactly the steps the values lost.
            active = np.take(np.asarray(active), indices, axis=axis)
        moved = var.with_data(
            np.take(np.asarray(data), indices, axis=axis), active=active
        )
        moved.attributes = {
            **var.attributes,
            "time_values": list(carried),
            TIME_UNITS_ATTR: units,
            TIME_CALENDAR_ATTR: calendar,
        }
        new_vars[name] = moved
    return self._rebuild(new_vars)

interp_calendar(target) #

Interpolate the values onto another dataset's stamps, across calendars (#1381).

:meth:convert_calendar's lossless counterpart. Where that one restamps the steps it has and drops the dates the target calendar lacks, this one interpolates the values onto the target's own stamps, so no step is lost and the two line up exactly — which is what :meth:concat or an operator between two runs needs.

Both axes are put on a common decimal-year scale — the year plus the fraction of it elapsed — which means the same thing in every calendar: a 360-day and a 365-day year both run from Y.0 to Y+1.0.

Parameters:

Name Type Description Default
target UgridDataset

The dataset whose stamps, units and calendar the result takes. Must sit on the same topology.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset on target's stamps, carrying its units and calendar.

Raises:

Type Description
AlignmentError

target sits on a different mesh.

ValueError

Either side carries no CF time units; this side has fewer than two steps to interpolate between; or the two spans do not overlap at all, so every step would come back a gap.

Note

A target stamp inside this dataset's span interpolates; one outside it is a gap, not an extrapolation. A partly overlapping target therefore comes back partly masked, and one that does not overlap at all is refused rather than answered as a fully-masked dataset.

See Also

convert_calendar: Restamps without interpolating, dropping absent dates.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def interp_calendar(self, target: UgridDataset) -> UgridDataset:
    """Interpolate the values onto another dataset's stamps, across calendars (#1381).

    :meth:`convert_calendar`'s lossless counterpart. Where that one restamps the steps it
    has and drops the dates the target calendar lacks, this one **interpolates the values**
    onto the target's own stamps, so no step is lost and the two line up exactly — which is
    what :meth:`concat` or an operator between two runs needs.

    Both axes are put on a common **decimal-year** scale — the year plus the fraction of it
    elapsed — which means the same thing in every calendar: a 360-day and a 365-day year
    both run from ``Y.0`` to ``Y+1.0``.

    Args:
        target: The dataset whose stamps, units and calendar the result takes. Must sit on
            the same topology.

    Returns:
        UgridDataset: A new dataset on ``target``'s stamps, carrying its units and calendar.

    Raises:
        AlignmentError: ``target`` sits on a different mesh.
        ValueError: Either side carries no CF time units; this side has fewer than two steps
            to interpolate between; or the two spans do not overlap at all, so every step
            would come back a gap.

    Note:
        A target stamp inside this dataset's span interpolates; one outside it is a **gap**,
        not an extrapolation. A partly overlapping target therefore comes back partly
        masked, and one that does not overlap at all is refused rather than answered as a
        fully-masked dataset.

    See Also:
        convert_calendar: Restamps without interpolating, dropping absent dates.
    """
    self._assert_same_topology(target, "interp_calendar")
    source_instants, _units, _calendar = self._calendar_instants("interp_calendar")
    target_instants, target_units, target_calendar = target._calendar_instants(
        "interp_calendar"
    )
    source_years = _decimal_years(source_instants)
    target_years = _decimal_years(target_instants)
    if source_years.size < 2:
        raise ValueError(
            f"interp_calendar() needs at least two steps to interpolate between, got "
            f"{source_years.size}."
        )
    if (
        target_years.max() < source_years.min()
        or target_years.min() > source_years.max()
    ):
        raise ValueError(
            "interp_calendar() got a target whose time span does not overlap this "
            "dataset's at all, so every step would come back a gap. Check that the two "
            "runs cover the same period."
        )
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time:
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(
                f"Variable {name!r} has no loaded data to interpolate."
            )
        moved = var.with_data(
            _timeseries.interp_axis(
                np.asarray(data), source_years, target_years, axis
            ),
            # As in `interp_like`: a static element mask is unaffected by re-stamping.
            active=None if var.active_has_time else _KEEP_ACTIVE,
        )
        moved.attributes = {
            **var.attributes,
            "time_values": list(target_instants),
            TIME_UNITS_ATTR: target_units,
            TIME_CALENDAR_ATTR: target_calendar,
        }
        new_vars[name] = moved
    return self._rebuild(new_vars)

to_image(variable_name=None, cell_size=None, cmap='viridis', method='nearest') #

Export a mesh variable as a colour-mapped RGB image (issue #1378).

An image is a grid of pixels, so the mesh is rasterised first and the raster's own :meth:Dataset.to_image does the colour mapping — which keeps the colours going through cleopatra, as all pyramids rendering does, and keeps one implementation of the mapping rather than two that can drift.

Parameters:

Name Type Description Default
variable_name str | None

Variable to render (default: the only one).

None
cell_size float | None

Pixel size in coordinate units. None (default) picks one that puts roughly 512 pixels across the mesh's longer side — a readable thumbnail without asking the caller to work out a resolution for a mesh whose units they may not know.

None
cmap str

Matplotlib colormap name.

'viridis'
method str

Rasterisation method, "nearest" (default) or "linear".

'nearest'

Returns:

Type Description
Any

PIL.Image.Image: The colour-mapped image. The pixels the rasterisation leaves

Any

empty — those outside the mesh footprint — are no-data, and so are rendered with

Any

the colormap's "bad" fill colour, exactly as the raster version renders them.

Any

Requires the viz extra.

Raises:

Type Description
ValueError

The variable is not one value per element, or no variable is selected and the dataset holds more than one.

See Also

to_dataset: The rasterisation this builds on, when you want the grid itself. plot: An annotated figure rather than a bare image.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_image(
    self,
    variable_name: str | None = None,
    cell_size: float | None = None,
    cmap: str = "viridis",
    method: str = "nearest",
) -> Any:
    """Export a mesh variable as a colour-mapped RGB image (issue #1378).

    An image is a grid of pixels, so the mesh is rasterised first and the raster's own
    :meth:`Dataset.to_image` does the colour mapping — which keeps the colours going
    through cleopatra, as all pyramids rendering does, and keeps one implementation of the
    mapping rather than two that can drift.

    Args:
        variable_name: Variable to render (default: the only one).
        cell_size: Pixel size in coordinate units. ``None`` (default) picks one that puts
            roughly 512 pixels across the mesh's longer side — a readable thumbnail
            without asking the caller to work out a resolution for a mesh whose units
            they may not know.
        cmap: Matplotlib colormap name.
        method: Rasterisation method, ``"nearest"`` (default) or ``"linear"``.

    Returns:
        PIL.Image.Image: The colour-mapped image. The pixels the rasterisation leaves
        empty — those outside the mesh footprint — are no-data, and so are rendered with
        the colormap's "bad" fill colour, exactly as the raster version renders them.
        Requires the ``viz`` extra.

    Raises:
        ValueError: The variable is not one value per element, or no variable is selected
            and the dataset holds more than one.

    See Also:
        to_dataset: The rasterisation this builds on, when you want the grid itself.
        plot: An annotated figure rather than a bare image.
    """
    var = self._facade_variable("to_image", variable_name)
    if var.has_time:
        raise ValueError(
            f"to_image() needs one value per element, but {var.name!r} is a time series "
            f"of {var.n_time_steps} steps. Select a step first, e.g. with isel(time=0)."
        )
    if cell_size is None:
        xmin, ymin, xmax, ymax = self.bounds
        # ~512 px across the longer side: a readable thumbnail without making the caller
        # reason about a resolution in coordinate units they may not know.
        cell_size = max(xmax - xmin, ymax - ymin) / 512.0
    grid = self.to_dataset(var.name, cell_size, method=method)
    return grid.to_image(cmap=cmap)

convert_units(target, variable_name=None) #

Convert variable values to target units (issue #1378).

Mesh variables carry a units attribute, so the raster's conversion applies unchanged — and it is the same affine table (:func:pyramids.dataset.ops.units.convert_array), so the two sides cannot disagree about what a Kelvin is.

No-data elements keep their sentinel rather than being converted as though they were data, which would otherwise turn -9999 into a plausible-looking temperature.

Parameters:

Name Type Description Default
target str

Target unit label (e.g. "celsius", "hPa", "knots").

required
variable_name str | None

Variable to convert. None (default) converts every variable that declares a unit; one already in target units passes through unchanged.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with converted values and the new unit recorded.

Raises:

Type Description
ValueError

A selected variable declares no source unit, or the (source, target) pair is not in the conversion table.

See Also

Dataset.convert_units: The raster counterpart, sharing this table.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def convert_units(
    self, target: str, variable_name: str | None = None
) -> UgridDataset:
    """Convert variable values to ``target`` units (issue #1378).

    Mesh variables carry a ``units`` attribute, so the raster's conversion applies
    unchanged — and it is the same affine table
    (:func:`pyramids.dataset.ops.units.convert_array`), so the two sides cannot disagree
    about what a Kelvin is.

    No-data elements keep their sentinel rather than being converted as though they were
    data, which would otherwise turn ``-9999`` into a plausible-looking temperature.

    Args:
        target: Target unit label (e.g. ``"celsius"``, ``"hPa"``, ``"knots"``).
        variable_name: Variable to convert. ``None`` (default) converts every variable
            that declares a unit; one already in ``target`` units passes through unchanged.

    Returns:
        UgridDataset: A new dataset with converted values and the new unit recorded.

    Raises:
        ValueError: A selected variable declares no source unit, or the
            ``(source, target)`` pair is not in the conversion table.

    See Also:
        Dataset.convert_units: The raster counterpart, sharing this table.
    """
    self._require_variable_name("convert_units", variable_name)
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        selected = variable_name is None or name == variable_name
        if not selected or var.units == target:
            new_vars[name] = var
            continue
        if not var.units:
            if variable_name is None:
                # A sweep over every variable skips the ones with nothing to convert from;
                # naming one explicitly is a request that must not pass silently.
                new_vars[name] = var
                continue
            raise ValueError(
                f"convert_units() cannot convert {name!r}: it declares no units to "
                f"convert from. Set its `units` first."
            )
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to convert.")
        values = np.asarray(data, dtype="float64")
        converted = convert_array(values, var.units, target)
        if var.nodata is not None:
            # The sentinel is not a measurement, so it keeps its value.
            converted = np.where(values == var.nodata, values, converted)
        moved = var.with_data(converted)
        moved.units = target
        moved.attributes = {**var.attributes, "units": target}
        new_vars[name] = moved
    return self._rebuild(new_vars)

to_dask_dataframe(variables=None, *, dropna=False, npartitions=1) #

Hand the mesh to dask in tidy form — the lazy sibling of :meth:to_dataframe.

The mesh's own frame is already tidy (one row per element and step), so this is the same shape wrapped in a dask dataframe rather than a different layout.

What is and is not deferred: a mesh's values live in memory, not in a per-element chunked store, so there is nothing to stream and the frame is built then partitioned. The result is a real dask graph — it composes with the rest of a dask pipeline and computes lazily from here on — but it does not reduce the peak memory of building it. That is the same thing :meth:NetCDF.to_dask_dataframe does for a cube with no on-disk store.

Parameters:

Name Type Description Default
variables Sequence[str] | None

Which data variables to include. None (default) takes them all.

None
dropna bool

Drop rows whose value is no-data. Defaults to False.

False
npartitions int

How many partitions to split the frame into. Defaults to 1.

1

Returns:

Type Description
Any

dask.dataframe.DataFrame: The tidy frame as a dask dataframe.

Raises:

Type Description
ImportError

dask (the lazy extra) or dask.dataframe (which needs pyarrow, the parquet extra) is not installed.

ValueError

npartitions is below 1, or a named variable does not exist.

See Also

to_dataframe: The eager pandas frame this wraps.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def to_dask_dataframe(
    self,
    variables: Sequence[str] | None = None,
    *,
    dropna: bool = False,
    npartitions: int = 1,
) -> Any:
    """Hand the mesh to dask in tidy form — the lazy sibling of :meth:`to_dataframe`.

    The mesh's own frame is already tidy (one row per element and step), so this is the
    same shape wrapped in a dask dataframe rather than a different layout.

    **What is and is not deferred:** a mesh's values live in memory, not in a per-element
    chunked store, so there is nothing to stream and the frame is built then partitioned.
    The result is a real dask graph — it composes with the rest of a dask pipeline and
    computes lazily from here on — but it does not reduce the peak memory of building it.
    That is the same thing :meth:`NetCDF.to_dask_dataframe` does for a cube with no
    on-disk store.

    Args:
        variables: Which data variables to include. ``None`` (default) takes them all.
        dropna: Drop rows whose value is no-data. Defaults to False.
        npartitions: How many partitions to split the frame into. Defaults to 1.

    Returns:
        dask.dataframe.DataFrame: The tidy frame as a dask dataframe.

    Raises:
        ImportError: dask (the ``lazy`` extra) or ``dask.dataframe`` (which needs pyarrow,
            the ``parquet`` extra) is not installed.
        ValueError: ``npartitions`` is below 1, or a named variable does not exist.

    See Also:
        to_dataframe: The eager pandas frame this wraps.
    """
    if npartitions < 1:
        raise ValueError(
            f"to_dask_dataframe() got npartitions={npartitions}; it must be at least 1."
        )
    import_dask("to_dask_dataframe() needs dask; install the `lazy` extra.")
    # dask.dataframe (dask-expr) imports pyarrow, which ships in the `parquet` extra rather
    # than `lazy`; guard it so a lazy-only install gets a hint, not a ModuleNotFoundError.
    require_optional(
        "dask.dataframe",
        "to_dask_dataframe() needs dask.dataframe, which requires pyarrow — install the "
        "`parquet` extra (e.g. `pip install pyramids-core[parquet]`).",
    )
    import dask.dataframe as dd

    frame = self.to_dataframe(variables, dropna=dropna)
    return dd.from_pandas(frame, npartitions=npartitions)

ffill(*, limit=None, dim=None) #

Forward-fill gaps along time from the last valid step.

Parameters:

Name Type Description Default
limit int | None

Maximum consecutive gaps one valid step may fill, or None for no limit.

None
dim str | None

The dimension to fill along. A mesh fills along "time" only, so any other name is refused; None means time. Defaults to None.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with each temporal variable's gaps carried forward

UgridDataset

from the previous valid step; static variables are unchanged.

Raises:

Type Description
ValueError

dim names anything but "time", no variable has a time dimension, or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def ffill(
    self, *, limit: int | None = None, dim: str | None = None
) -> UgridDataset:
    """Forward-fill gaps along time from the last valid step.

    Args:
        limit: Maximum consecutive gaps one valid step may fill, or ``None`` for no limit.
        dim: The dimension to fill along. A mesh fills along ``"time"`` only, so any other
            name is refused; ``None`` means time. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with each temporal variable's gaps carried forward
        from the previous valid step; static variables are unchanged.

    Raises:
        ValueError: ``dim`` names anything but ``"time"``, no variable has a time
            dimension, or a temporal variable has no loaded data.
    """
    self._check_time_dim("ffill", dim)
    return self._transform_time(
        "ffill", lambda d, axis: pushed(d, axis, limit, False)
    )

bfill(*, limit=None, dim=None) #

Back-fill gaps along time from the next valid step.

Parameters:

Name Type Description Default
limit int | None

Maximum consecutive gaps one valid step may fill, or None for no limit.

None
dim str | None

The dimension to fill along. A mesh fills along "time" only, so any other name is refused; None means time. Defaults to None.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with each temporal variable's gaps carried backward

UgridDataset

from the next valid step; static variables are unchanged.

Raises:

Type Description
ValueError

dim names anything but "time", no variable has a time dimension, or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def bfill(
    self, *, limit: int | None = None, dim: str | None = None
) -> UgridDataset:
    """Back-fill gaps along time from the next valid step.

    Args:
        limit: Maximum consecutive gaps one valid step may fill, or ``None`` for no limit.
        dim: The dimension to fill along. A mesh fills along ``"time"`` only, so any other
            name is refused; ``None`` means time. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with each temporal variable's gaps carried backward
        from the next valid step; static variables are unchanged.

    Raises:
        ValueError: ``dim`` names anything but ``"time"``, no variable has a time
            dimension, or a temporal variable has no loaded data.
    """
    self._check_time_dim("bfill", dim)
    return self._transform_time(
        "bfill", lambda d, axis: pushed(d, axis, limit, True)
    )

interpolate_na(*, method='linear', limit=None, use_coordinate=True, dim=None) #

Fill each interior time gap by interpolating between the steps on either side.

Distance is measured along the time coordinate by default, so unevenly spaced steps weight their neighbours accordingly; pass use_coordinate=False to measure by step position instead. A leading or trailing gap has only one neighbour and is left alone.

Parameters:

Name Type Description Default
method str

One of "linear" (distance-weighted), "nearest", or the scipy spline kinds "slinear" / "quadratic" / "cubic" (each falling back to linear on a variable with too few valid steps). Defaults to "linear".

'linear'
limit int | None

Maximum consecutive gaps a run may fill, or None for no limit.

None
use_coordinate bool

Measure distance along the time coordinate rather than by step position. With time values [0, 1, 10] and a gap at the middle step, the coordinate reading fills 1.0 and the positional reading 5.0. Date-like coordinates count as distances too (converted to nanoseconds), so unevenly spaced dates weight their neighbours; a coordinate with no measurable spacing (plain labels) falls back to step positions. Defaults to True.

True
dim str | None

The dimension to interpolate along. A mesh interpolates along "time" only, so any other name is refused; None means time. Defaults to None.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with each temporal variable's interior gaps

UgridDataset

interpolated along time; static variables are unchanged.

Raises:

Type Description
ValueError

method is not one of the accepted interpolations; no variable has a time dimension; or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def interpolate_na(
    self,
    *,
    method: str = "linear",
    limit: int | None = None,
    use_coordinate: bool = True,
    dim: str | None = None,
) -> UgridDataset:
    """Fill each interior time gap by interpolating between the steps on either side.

    Distance is measured along the time coordinate by default, so unevenly spaced steps
    weight their neighbours accordingly; pass ``use_coordinate=False`` to measure by step
    position instead. A leading or trailing gap has only one neighbour and is left alone.

    Args:
        method: One of ``"linear"`` (distance-weighted), ``"nearest"``, or the scipy spline
            kinds ``"slinear"`` / ``"quadratic"`` / ``"cubic"`` (each falling back to linear on
            a variable with too few valid steps). Defaults to ``"linear"``.
        limit: Maximum consecutive gaps a run may fill, or ``None`` for no limit.
        use_coordinate: Measure distance along the time coordinate rather than by step
            position. With time values ``[0, 1, 10]`` and a gap at the middle step, the
            coordinate reading fills ``1.0`` and the positional reading ``5.0``. Date-like
            coordinates count as distances too (converted to nanoseconds), so unevenly
            spaced dates weight their neighbours; a coordinate with no measurable spacing
            (plain labels) falls back to step positions. Defaults to ``True``.
        dim: The dimension to interpolate along. A mesh interpolates along ``"time"``
            only, so any other name is refused; ``None`` means time. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with each temporal variable's interior gaps
        interpolated along time; static variables are unchanged.

    Raises:
        ValueError: ``method`` is not one of the accepted interpolations; no variable has a
            time dimension; or a temporal variable has no loaded data.
    """
    if method not in INTERP_METHODS:
        # Validate up front, before the time check, so a bogus method is reported as such
        # even on a mesh with no temporal variable — matching the raster interpolate_na.
        raise ValueError(
            f"interpolate_na() takes method="
            f"{' or '.join(repr(one) for one in INTERP_METHODS)}, got {method!r}."
        )

    self._check_time_dim("interpolate_na", dim)
    stamps = self.time_values if use_coordinate else None
    axis_values = None
    if stamps is not None:
        axis_values = _axis_distances(stamps)

    def _fill(data: np.ndarray, axis: int) -> np.ndarray:
        size = data.shape[axis]
        if axis_values is not None and axis_values.shape[0] == size:
            positions = axis_values
        else:
            positions = np.arange(size, dtype="float64")
        return np.asarray(interpolated(data, axis, positions, method, limit))

    return self._transform_time("interpolate_na", _fill)

rolling(window, how='mean', *, center=False, min_periods=None, q=None, dim=None) #

Rolling-window reduction along time for every temporal variable.

Each time step becomes a statistic of the window of steps it owns (ending at it, or centred on it), cut where the window runs off the axis. Gaps are skipped; a step whose window holds fewer than min_periods valid cells is NaN. The time dimension keeps its length.

Parameters:

Name Type Description Default
window int

Steps per window.

required
how str

The reduction over each window ("mean", "sum", "min", "max", "std", "var", "median", "quantile"). Defaults to "mean".

'mean'
center bool

Centre each window on its step rather than ending at it. Defaults to False.

False
min_periods int | None

Valid cells a window needs before its step holds a value. None means the full window, matching the raster rolling, so a step whose window runs off the axis is NaN rather than a partial statistic. Defaults to None.

None
q float | None

The quantile in [0, 1], required when how="quantile" and rejected otherwise. Defaults to None.

None
dim str | None

The dimension to roll along. A mesh rolls along "time" only, so any other name is refused; None means time. Defaults to None.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with each temporal variable replaced by its rolling

UgridDataset

statistic along time; static variables are unchanged.

Raises:

Type Description
ValueError

how is not a known reduction; q is given for a non-quantile how or missing for how="quantile"; window is below 1; min_periods falls outside [1, window]; dim names anything but "time"; no variable has a time dimension; or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def rolling(
    self,
    window: int,
    how: str = "mean",
    *,
    center: bool = False,
    min_periods: int | None = None,
    q: float | None = None,
    dim: str | None = None,
) -> UgridDataset:
    """Rolling-window reduction along time for every temporal variable.

    Each time step becomes a statistic of the window of steps it owns (ending at it, or
    centred on it), cut where the window runs off the axis. Gaps are skipped; a step whose
    window holds fewer than ``min_periods`` valid cells is NaN. The time dimension keeps
    its length.

    Args:
        window: Steps per window.
        how: The reduction over each window (``"mean"``, ``"sum"``, ``"min"``, ``"max"``,
            ``"std"``, ``"var"``, ``"median"``, ``"quantile"``). Defaults to ``"mean"``.
        center: Centre each window on its step rather than ending at it. Defaults to False.
        min_periods: Valid cells a window needs before its step holds a value. ``None``
            means the full ``window``, matching the raster `rolling`, so a step whose
            window runs off the axis is NaN rather than a partial statistic. Defaults to
            ``None``.
        q: The quantile in ``[0, 1]``, required when ``how="quantile"`` and rejected
            otherwise. Defaults to ``None``.
        dim: The dimension to roll along. A mesh rolls along ``"time"`` only, so any
            other name is refused; ``None`` means time. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with each temporal variable replaced by its rolling
        statistic along time; static variables are unchanged.

    Raises:
        ValueError: ``how`` is not a known reduction; ``q`` is given for a non-quantile
            ``how`` or missing for ``how="quantile"``; ``window`` is below 1;
            ``min_periods`` falls outside ``[1, window]``; ``dim`` names anything but
            ``"time"``; no variable has a time dimension; or a temporal variable has no
            loaded data.
    """
    if how not in _ROLLING_HOWS:
        # Restrict to the documented statistics. The counting reductions
        # (count/all/any) are excluded on purpose: a window's all/any flag carries the
        # 255 FLAG_NO_DATA sentinel, which would surface as a literal data value here.
        raise ValueError(
            f"rolling how must be one of {sorted(_ROLLING_HOWS)}, got {how!r}."
        )
    # Same guard as every other along-time member, through the shared check rather than
    # a second copy of it with its own wording.
    self._check_time_dim("rolling", dim)
    if how == "quantile" and q is None:
        raise ValueError("rolling(how='quantile') needs q in [0, 1].")
    if how != "quantile" and q is not None:
        raise ValueError(
            f"rolling(q=...) is only valid with how='quantile', not {how!r}."
        )
    if window < 1:
        raise ValueError(f"rolling: window must be >= 1, got {window!r}.")
    # `None` means the full window, as the raster rolling defaults — a step whose window
    # runs off the axis then has no statistic rather than a partial one.
    needed = window if min_periods is None else int(min_periods)
    if not 1 <= needed <= window:
        raise ValueError(
            f"rolling: min_periods must be between 1 and window ({window}), got "
            f"{min_periods!r}."
        )

    def _roll(data: np.ndarray, axis: int) -> np.ndarray:
        moved = np.moveaxis(data, axis, 0)
        size = moved.shape[0]
        out = np.full_like(moved, np.nan, dtype="float64")
        for step in range(size):
            members = window_members(step, size, window, center)
            block = moved[members]
            valid = np.sum(~np.isnan(block), axis=0)
            reduced = reduce_axis(block, 0, how, True, None, q)
            out[step] = np.where(valid >= needed, reduced, np.nan)
        return np.moveaxis(out, 0, axis)

    return self._transform_time("rolling", _roll)

isel(time=None, *, element=None) #

Select by position along the time axis, the element axis, or both.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.isel. Over time an integer selects a single step and collapses the time dimension (the variables become static); a slice or sequence keeps the time dimension, trimmed to the chosen steps. Over element the selection is a topology change: the chosen faces are kept and the mesh is renumbered around them (as :meth:clip does), so the result is a smaller mesh. Giving both applies the element selection first, then the time selection.

Parameters:

Name Type Description Default
time int | slice | list[int] | ndarray | None

An int step, a slice, or a sequence of integer step positions. None (the default) leaves the time axis alone.

None
element int | slice | list[int] | ndarray | None

An int face index, a slice, or a sequence of face indices. None (the default) leaves the mesh alone.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with the selection applied.

Raises:

Type Description
ValueError

Neither time nor element was given, or time was asked of a dataset with no time dimension.

IndexError

A face index is out of range for this mesh.

Examples:

  • Keep one face, renumbering the mesh around it:
    >>> import numpy as np
    >>> from pyramids.netcdf.ugrid import UgridDataset
    >>> mesh = UgridDataset.from_arrays(
    ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
    ...     data={"depth": np.array([2.0, 4.0])},
    ... )
    >>> one = mesh.isel(element=0)
    >>> one.n_face, one.n_node
    (1, 3)
    >>> one["depth"].data.tolist()
    [2.0]
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def isel(
    self,
    time: int | slice | list[int] | np.ndarray | None = None,
    *,
    element: int | slice | list[int] | np.ndarray | None = None,
) -> UgridDataset:
    """Select by position along the time axis, the element axis, or both.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.isel`. Over **time** an integer
    selects a single step and collapses the time dimension (the variables become static);
    a slice or sequence keeps the time dimension, trimmed to the chosen steps. Over
    **element** the selection is a topology change: the chosen faces are kept and the mesh
    is renumbered around them (as :meth:`clip` does), so the result is a smaller mesh.
    Giving both applies the element selection first, then the time selection.

    Args:
        time: An ``int`` step, a ``slice``, or a sequence of integer step positions.
            ``None`` (the default) leaves the time axis alone.
        element: An ``int`` face index, a ``slice``, or a sequence of face indices.
            ``None`` (the default) leaves the mesh alone.

    Returns:
        UgridDataset: A new dataset with the selection applied.

    Raises:
        ValueError: Neither ``time`` nor ``element`` was given, or ``time`` was asked of a
            dataset with no time dimension.
        IndexError: A face index is out of range for this mesh.

    Examples:
        - Keep one face, renumbering the mesh around it:
            ```python
            >>> import numpy as np
            >>> from pyramids.netcdf.ugrid import UgridDataset
            >>> mesh = UgridDataset.from_arrays(
            ...     node_x=np.array([0.0, 1.0, 1.0, 0.0]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=np.array([[0, 1, 2], [0, 2, 3]]),
            ...     data={"depth": np.array([2.0, 4.0])},
            ... )
            >>> one = mesh.isel(element=0)
            >>> one.n_face, one.n_node
            (1, 3)
            >>> one["depth"].data.tolist()
            [2.0]

            ```
    """
    if time is None and element is None:
        raise ValueError("isel needs `time`, `element`, or both.")
    if element is not None:
        selected = self._select_elements(element)
        return selected if time is None else selected.isel(time)
    n = self._time_length("isel")
    if isinstance(time, (int, np.integer)):
        return self._collapse_to_step(int(time))
    if isinstance(time, slice):
        indices = np.arange(n)[time]
    else:
        indices = np.asarray(time, dtype=np.intp)
    return self._select_steps(indices)

head(n=5) #

Keep the first n time steps (fewer if the axis is shorter).

Parameters:

Name Type Description Default
n int

Number of leading steps to keep. Defaults to 5.

5

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset trimmed to the first n steps.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def head(self, n: int = 5) -> UgridDataset:
    """Keep the first ``n`` time steps (fewer if the axis is shorter).

    Args:
        n: Number of leading steps to keep. Defaults to 5.

    Returns:
        UgridDataset: A new dataset trimmed to the first ``n`` steps.

    Raises:
        ValueError: No variable has a time dimension.
    """
    length = self._time_length("head")
    return self._select_steps(np.arange(min(n, length)))

tail(n=5) #

Keep the last n time steps (fewer if the axis is shorter).

Parameters:

Name Type Description Default
n int

Number of trailing steps to keep. Defaults to 5.

5

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset trimmed to the last n steps.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def tail(self, n: int = 5) -> UgridDataset:
    """Keep the last ``n`` time steps (fewer if the axis is shorter).

    Args:
        n: Number of trailing steps to keep. Defaults to 5.

    Returns:
        UgridDataset: A new dataset trimmed to the last ``n`` steps.

    Raises:
        ValueError: No variable has a time dimension.
    """
    length = self._time_length("tail")
    return self._select_steps(np.arange(max(length - n, 0), length))

thin(step) #

Keep every step-th time step.

Parameters:

Name Type Description Default
step int

Stride; must be >= 1.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset keeping every step-th step.

Raises:

Type Description
ValueError

step is less than 1, or no variable is temporal.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def thin(self, step: int) -> UgridDataset:
    """Keep every ``step``-th time step.

    Args:
        step: Stride; must be >= 1.

    Returns:
        UgridDataset: A new dataset keeping every ``step``-th step.

    Raises:
        ValueError: ``step`` is less than 1, or no variable is temporal.
    """
    if step < 1:
        raise ValueError(f"thin step must be >= 1, got {step}.")
    length = self._time_length("thin")
    return self._select_steps(np.arange(0, length, step))

drop_isel(indices) #

Drop the time steps at indices by position, keeping the rest.

Parameters:

Name Type Description Default
indices int | list[int] | ndarray

A step position, or a sequence of them, to drop (negative indices count from the end).

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset without the dropped steps.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def drop_isel(self, indices: int | list[int] | np.ndarray) -> UgridDataset:
    """Drop the time steps at ``indices`` by position, keeping the rest.

    Args:
        indices: A step position, or a sequence of them, to drop (negative indices
            count from the end).

    Returns:
        UgridDataset: A new dataset without the dropped steps.

    Raises:
        ValueError: No variable has a time dimension.
    """
    length = self._time_length("drop_isel")
    drop = {int(i) % length for i in np.atleast_1d(np.asarray(indices))}
    keep = np.array([i for i in range(length) if i not in drop], dtype=np.intp)
    return self._select_steps(keep)

squeeze() #

Drop the time dimension when it has length 1; otherwise return unchanged.

Mirrors :meth:pyramids.netcdf.NetCDF.squeeze for the time axis: a single-step temporal variable becomes static, a multi-step one is left alone.

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with single-step temporal variables collapsed to

UgridDataset

static, or self when there is nothing to squeeze.

Raises:

Type Description
ValueError

A single-step temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def squeeze(self) -> UgridDataset:
    """Drop the time dimension when it has length 1; otherwise return unchanged.

    Mirrors :meth:`pyramids.netcdf.NetCDF.squeeze` for the time axis: a single-step
    temporal variable becomes static, a multi-step one is left alone.

    Returns:
        UgridDataset: A new dataset with single-step temporal variables collapsed to
        static, or ``self`` when there is nothing to squeeze.

    Raises:
        ValueError: A single-step temporal variable has no loaded data.
    """
    # Decide per variable, not from the first temporal one: with mixed time lengths a
    # later single-step variable must still be squeezed even if the first has many steps.
    if not any(
        var.has_time and var.n_time_steps == 1
        for var in self._data_variables.values()
    ):
        return self
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time or var.n_time_steps != 1:
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to squeeze.")
        # Squeezing the size-1 time axis is taking its single step, so collapse a per-step
        # mask to that step (`mask[0]`) rather than letting the implicit carry drop it as a
        # now-rank-mismatched 2-D mask (review L3). A static mask passes straight through.
        new_vars[name] = _static_from(
            var,
            np.squeeze(np.asarray(data), axis=axis),
            axis,
            active=var._time_sliced_active(0, None),
        )
    return self._rebuild(new_vars)

diff(n=1) #

Discrete difference along time (out[i] = x[i] - x[i-1]), n times.

The time dimension shortens by n; a time_values coordinate, if present, drops its first n entries to stay aligned with the result.

Parameters:

Name Type Description Default
n int

The number of successive differences. Defaults to 1.

1

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with each temporal variable differenced along time

UgridDataset

(its time axis shorter by n); static variables are unchanged.

Raises:

Type Description
ValueError

No variable has a time dimension, or a temporal variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def diff(self, n: int = 1) -> UgridDataset:
    """Discrete difference along time (``out[i] = x[i] - x[i-1]``), ``n`` times.

    The time dimension shortens by ``n``; a ``time_values`` coordinate, if present, drops
    its first ``n`` entries to stay aligned with the result.

    Args:
        n: The number of successive differences. Defaults to 1.

    Returns:
        UgridDataset: A new dataset with each temporal variable differenced along time
        (its time axis shorter by ``n``); static variables are unchanged.

    Raises:
        ValueError: No variable has a time dimension, or a temporal variable has no
            loaded data.
    """
    self._require_temporal("diff")
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time:
            new_vars[name] = var
            continue
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to diff.")
        diffed = np.diff(gaps_as_nan(np.asarray(data), var.nodata), n=n, axis=axis)
        new_var = var.with_data(diffed)
        times = var.attributes.get("time_values")
        if times is not None:
            new_var.attributes = {**var.attributes, "time_values": list(times[n:])}
        new_vars[name] = new_var
    return self._rebuild(new_vars)

argmin() #

The time-step position of each element's minimum.

Returns:

Name Type Description
UgridDataset UgridDataset

Static int64 variables holding the step index of the minimum,

UgridDataset

declaring -1 for an element with no valid step.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def argmin(self) -> UgridDataset:
    """The time-step position of each element's minimum.

    Returns:
        UgridDataset: Static ``int64`` variables holding the step index of the minimum,
        declaring ``-1`` for an element with no valid step.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self._extremum_along_time("argmin", largest=False, as_coordinate=False)

argmax() #

The time-step position of each element's maximum.

Returns:

Name Type Description
UgridDataset UgridDataset

Static int64 variables holding the step index of the maximum,

UgridDataset

declaring -1 for an element with no valid step.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def argmax(self) -> UgridDataset:
    """The time-step position of each element's maximum.

    Returns:
        UgridDataset: Static ``int64`` variables holding the step index of the maximum,
        declaring ``-1`` for an element with no valid step.

    Raises:
        ValueError: No variable has a time dimension.
    """
    return self._extremum_along_time("argmax", largest=True, as_coordinate=False)

idxmin() #

The time coordinate of each element's minimum.

Where :meth:argmin answers a step position, this answers the value of the time coordinate at that step, so it needs numeric time coordinates.

Returns:

Name Type Description
UgridDataset UgridDataset

Static float64 variables holding the time coordinate of the

UgridDataset

minimum, NaN where an element has no valid step.

Raises:

Type Description
ValueError

No variable has a time dimension, or the time coordinates are date-like rather than numeric (use argmin / argmax for the step position instead).

Source code in src/pyramids/netcdf/ugrid/dataset.py
def idxmin(self) -> UgridDataset:
    """The time **coordinate** of each element's minimum.

    Where :meth:`argmin` answers a step position, this answers the value of the time
    coordinate at that step, so it needs numeric time coordinates.

    Returns:
        UgridDataset: Static ``float64`` variables holding the time coordinate of the
        minimum, NaN where an element has no valid step.

    Raises:
        ValueError: No variable has a time dimension, or the time coordinates are
            date-like rather than numeric (use `argmin` / `argmax` for the step
            position instead).
    """
    return self._extremum_along_time("idxmin", largest=False, as_coordinate=True)

idxmax() #

The time coordinate of each element's maximum.

Returns:

Name Type Description
UgridDataset UgridDataset

Static float64 variables holding the time coordinate of the

UgridDataset

maximum, NaN where an element has no valid step.

Raises:

Type Description
ValueError

No variable has a time dimension, or the time coordinates are date-like rather than numeric (use argmin / argmax for the step position instead).

Source code in src/pyramids/netcdf/ugrid/dataset.py
def idxmax(self) -> UgridDataset:
    """The time **coordinate** of each element's maximum.

    Returns:
        UgridDataset: Static ``float64`` variables holding the time coordinate of the
        maximum, NaN where an element has no valid step.

    Raises:
        ValueError: No variable has a time dimension, or the time coordinates are
            date-like rather than numeric (use `argmin` / `argmax` for the step
            position instead).
    """
    return self._extremum_along_time("idxmax", largest=True, as_coordinate=True)

sel(time=None, *, method=None, tolerance=None) #

Select time steps by coordinate value, exactly or by nearest.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.sel over time. A scalar selects one step and collapses the time dimension; a sequence keeps it. Values are matched against the dataset's :attr:time_values (which fall back to step positions when the file carries no explicit time coordinate). method="nearest" snaps each value to the closest coordinate instead of requiring an exact hit, and tolerance caps how far it may snap — the same contract the raster sel uses, including raising KeyError (not ValueError) when a snap would exceed tolerance.

Parameters:

Name Type Description Default
time Any

A coordinate value, or a sequence of them.

None
method str | None

None (the default) matches exactly; "nearest" snaps to the closest coordinate, which needs numeric coordinates.

None
tolerance float | None

The furthest a method="nearest" snap may travel. Only valid with "nearest", and must not be negative.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with the selected steps.

Raises:

Type Description
ValueError

No time dimension; an unknown method; tolerance without method="nearest" or negative; a value is not among the coordinates (exact match); or "nearest" was asked of non-numeric coordinates.

KeyError

A "nearest" snap would exceed tolerance.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sel(
    self,
    time: Any = None,
    *,
    method: str | None = None,
    tolerance: float | None = None,
) -> UgridDataset:
    """Select time steps by coordinate value, exactly or by nearest.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.sel` over time. A scalar selects
    one step and collapses the time dimension; a sequence keeps it. Values are matched
    against the dataset's :attr:`time_values` (which fall back to step positions when the
    file carries no explicit time coordinate). ``method="nearest"`` snaps each value to the
    closest coordinate instead of requiring an exact hit, and ``tolerance`` caps how far it
    may snap — the same contract the raster ``sel`` uses, including raising ``KeyError`` (not
    ``ValueError``) when a snap would exceed ``tolerance``.

    Args:
        time: A coordinate value, or a sequence of them.
        method: ``None`` (the default) matches exactly; ``"nearest"`` snaps to the closest
            coordinate, which needs numeric coordinates.
        tolerance: The furthest a ``method="nearest"`` snap may travel. Only valid with
            ``"nearest"``, and must not be negative.

    Returns:
        UgridDataset: A new dataset with the selected steps.

    Raises:
        ValueError: No time dimension; an unknown ``method``; ``tolerance`` without
            ``method="nearest"`` or negative; a value is not among the coordinates (exact
            match); or ``"nearest"`` was asked of non-numeric coordinates.
        KeyError: A ``"nearest"`` snap would exceed ``tolerance``.
    """
    if time is None:
        # `time` is optional in the signature for parity with the raster `sel`, but a
        # missing value has no meaning here. Say so, as `isel` does, instead of
        # reporting that the coordinate [None] was not found.
        raise ValueError(
            "sel needs a time value to select; pass one, or use isel() to select by "
            "position."
        )
    coords = self._time_coords("sel")
    if method not in (None, "nearest"):
        raise ValueError(f"sel: method must be None or 'nearest', got {method!r}.")
    if tolerance is not None:
        if method != "nearest":
            raise ValueError("sel: tolerance is only valid with method='nearest'.")
        if float(tolerance) < 0:
            raise ValueError(
                f"sel: tolerance must not be negative, got {tolerance!r}."
            )
    wanted = list(time) if isinstance(time, (list, tuple, np.ndarray)) else [time]
    positions = _resolve_time_positions(coords, wanted, method, tolerance)
    if isinstance(time, (list, tuple, np.ndarray)):
        result = self._select_steps(np.asarray(positions, dtype=np.intp))
    else:
        result = self.isel(positions[0])
    return result

drop_sel(values) #

Drop the time steps whose coordinate is in values, keeping the rest.

Parameters:

Name Type Description Default
values Any

A coordinate value, or a sequence of them, to drop.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset without the steps whose coordinate is in values.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def drop_sel(self, values: Any) -> UgridDataset:
    """Drop the time steps whose coordinate is in ``values``, keeping the rest.

    Args:
        values: A coordinate value, or a sequence of them, to drop.

    Returns:
        UgridDataset: A new dataset without the steps whose coordinate is in ``values``.

    Raises:
        ValueError: No variable has a time dimension.
    """
    coords = self._time_coords("drop_sel")
    drop = (
        set(values)
        if isinstance(values, (list, tuple, set))
        else {*np.atleast_1d(np.asarray(values)).tolist()}
    )
    keep = [i for i, coord in enumerate(coords) if coord not in drop]
    return self._select_steps(np.asarray(keep, dtype=np.intp))

sortby() #

Sort the time steps by their coordinate value (stable).

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with steps ordered by ascending time coordinate.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def sortby(self) -> UgridDataset:
    """Sort the time steps by their coordinate value (stable).

    Returns:
        UgridDataset: A new dataset with steps ordered by ascending time coordinate.

    Raises:
        ValueError: No variable has a time dimension.
    """
    coords = self._time_coords("sortby")
    order = np.argsort(np.asarray(coords), kind="stable")
    return self._select_steps(order)

drop_duplicates() #

Keep the first step of each distinct time coordinate value.

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with duplicate-coordinate steps removed, first kept.

Raises:

Type Description
ValueError

No variable has a time dimension.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def drop_duplicates(self) -> UgridDataset:
    """Keep the first step of each distinct time coordinate value.

    Returns:
        UgridDataset: A new dataset with duplicate-coordinate steps removed, first kept.

    Raises:
        ValueError: No variable has a time dimension.
    """
    coords = self._time_coords("drop_duplicates")
    seen: set = set()
    keep: list[int] = []
    for i, coord in enumerate(coords):
        if coord not in seen:
            seen.add(coord)
            keep.append(i)
    return self._select_steps(np.asarray(keep, dtype=np.intp))

dropna(how='any', thresh=None, *, dim=None) #

Drop time steps that do not hold enough valid cells.

A step is kept only when every temporal variable meets the threshold at that step, so the variables stay time-aligned. how="any" requires every cell of a variable to be valid (a single gap drops the step); how="all" requires at least one; thresh overrides how with an explicit valid-cell count per variable.

Parameters:

Name Type Description Default
how str

"any" or "all". Defaults to "any".

'any'
thresh int | None

Explicit minimum valid-cell count per variable, overriding how.

None
dim str | None

The dimension to drop along. A mesh drops along "time" only, so any other name is refused; None means time. Defaults to None.

None

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset with the surviving steps.

Raises:

Type Description
ValueError

how is neither "any" nor "all"; dim names anything but "time"; no variable has a time dimension; a temporal variable has no loaded data; or the threshold would drop every step, which would leave a temporal dataset with no steps for anything downstream to read.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def dropna(
    self, how: str = "any", thresh: int | None = None, *, dim: str | None = None
) -> UgridDataset:
    """Drop time steps that do not hold enough valid cells.

    A step is kept only when **every** temporal variable meets the threshold at that
    step, so the variables stay time-aligned. ``how="any"`` requires every cell of a
    variable to be valid (a single gap drops the step); ``how="all"`` requires at least
    one; ``thresh`` overrides ``how`` with an explicit valid-cell count per variable.

    Args:
        how: ``"any"`` or ``"all"``. Defaults to ``"any"``.
        thresh: Explicit minimum valid-cell count per variable, overriding ``how``.
        dim: The dimension to drop along. A mesh drops along ``"time"`` only, so any other
            name is refused; ``None`` means time. Defaults to ``None``.

    Returns:
        UgridDataset: A new dataset with the surviving steps.

    Raises:
        ValueError: ``how`` is neither ``"any"`` nor ``"all"``; ``dim`` names anything but
            ``"time"``; no variable has a time dimension; a temporal variable has no
            loaded data; or the threshold would drop **every** step, which would leave a
            temporal dataset with no steps for anything downstream to read.
    """
    if how not in ("any", "all"):
        raise ValueError(f"dropna how must be 'any' or 'all', got {how!r}.")
    self._check_time_dim("dropna", dim)
    temporal = self._require_temporal("dropna")
    length = self._time_length("dropna")
    keep = np.ones(length, dtype=bool)
    for name in temporal:
        var = self._data_variables[name]
        axis = cast("int", var.time_index)
        data = var.data
        if data is None:
            raise ValueError(f"Variable {name!r} has no loaded data to dropna.")
        moved = np.moveaxis(gaps_as_nan(np.asarray(data), var.nodata), axis, 0)
        flat = moved.reshape(moved.shape[0], -1)
        per_step_valid = np.sum(~np.isnan(flat), axis=1)
        needed = flat.shape[1] if how == "any" else 1
        if thresh is not None:
            needed = thresh
        keep &= per_step_valid >= needed
    if not keep.any():
        # Returning a zero-length time axis would leave a "temporal" dataset with no
        # steps, which nothing downstream can read; the raster dropna refuses too.
        raise ValueError(
            f"dropna(how={how!r}, thresh={thresh!r}) would drop every one of the "
            f"{length} time step(s); nothing would be left."
        )
    return self._select_steps(np.flatnonzero(keep))

concat(others) #

Concatenate same-topology datasets along time.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.concat. Every dataset must sit on the same mesh. Each temporal variable's data is concatenated along its time axis (and its time_values coordinate, when present); a static variable is taken from self unchanged. The variable set must match across datasets.

A per-step active mask (:attr:MeshVariable.active of shape (n_time, n_element)) is dropped on concatenation — the parts' masks are not joined along time, and the concatenated time length no longer matches self's mask, so the implicit carry discards it (issue #1331). A static (n_element,) mask survives, since it applies to every step. Re-attach a per-step mask after concatenating if you need one.

Parameters:

Name Type Description Default
others UgridDataset | list[UgridDataset]

One dataset, or a list of them, to append after self in order.

required

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset spanning the concatenated time axis.

Raises:

Type Description
AlignmentError

A dataset sits on a different mesh. Note this is not a ValueError subclass, so a caller catching ValueError around concat has to catch AlignmentError instead.

ValueError

A dataset carries a different variable set, or a variable has no loaded data.

Source code in src/pyramids/netcdf/ugrid/dataset.py
@_joins_meshes
def concat(self, others: UgridDataset | list[UgridDataset]) -> UgridDataset:
    """Concatenate same-topology datasets along time.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.concat`. Every dataset must sit
    on the same mesh. Each temporal variable's data is concatenated along its time axis
    (and its ``time_values`` coordinate, when present); a static variable is taken from
    ``self`` unchanged. The variable set must match across datasets.

    A **per-step** active mask (:attr:`MeshVariable.active` of shape ``(n_time, n_element)``)
    is **dropped** on concatenation — the parts' masks are not joined along time, and the
    concatenated time length no longer matches ``self``'s mask, so the implicit carry
    discards it (issue #1331). A **static** ``(n_element,)`` mask survives, since it applies
    to every step. Re-attach a per-step mask after concatenating if you need one.

    Args:
        others: One dataset, or a list of them, to append after ``self`` in order.

    Returns:
        UgridDataset: A new dataset spanning the concatenated time axis.

    Raises:
        AlignmentError: A dataset sits on a different mesh. Note this is **not** a
            `ValueError` subclass, so a caller catching `ValueError` around `concat` has
            to catch `AlignmentError` instead.
        ValueError: A dataset carries a different variable set, or a variable has no
            loaded data.
    """
    parts = [
        self,
        *([others] if isinstance(others, UgridDataset) else list(others)),
    ]
    for other in parts[1:]:
        self._assert_same_topology(other, "concat")
        if set(other._data_variables) != set(self._data_variables):
            raise ValueError(
                "concat requires the same variables in every dataset; got "
                f"{sorted(self._data_variables)} vs {sorted(other._data_variables)}."
            )
    new_vars: dict[str, MeshVariable] = {}
    for name, var in self._data_variables.items():
        if not var.has_time:
            # Static in self: refuse if any other part has it temporal, rather than
            # silently drop that part's time series (the mirror of the temporal-in-self
            # / static-in-other case _concat_temporal_variable rejects).
            if any(part._data_variables[name].has_time for part in parts[1:]):
                raise ValueError(
                    f"concat: variable {name!r} is static in one dataset but temporal "
                    "in another; they cannot be joined along time."
                )
            new_vars[name] = var  # a static variable is taken from self, as-is
        else:
            new_vars[name] = _concat_temporal_variable(name, var, parts)
    return self._rebuild(new_vars)

merge(others, *, compat='no_conflicts') #

Merge the variables of same-topology datasets into one.

The mesh counterpart of :meth:pyramids.netcdf.NetCDF.merge. Every dataset must sit on the same mesh; the union of their variables is returned. A variable name present in more than one dataset is a conflict and is refused.

Parameters:

Name Type Description Default
others UgridDataset | list[UgridDataset]

One dataset, or a list of them, whose variables join self's. Under the class spelling UgridDataset.merge([a, b, c]) this one argument is the whole join: its first element becomes self and the rest are merged onto it.

required
compat str

How to handle a variable name present in more than one dataset -- "no_conflicts" refuses the collision, "override" keeps the value from the first dataset in join order that carries the name: self, then each of others in turn. That is self's only when self has the variable; when it does not, the first of others carrying it wins. (Under the class spelling UgridDataset.merge([a, b, c]), self is a.) Defaults to "no_conflicts".

'no_conflicts'

Returns:

Name Type Description
UgridDataset UgridDataset

A new dataset carrying every variable.

Raises:

Type Description
AlignmentError

A dataset sits on a different mesh.

ValueError

An unknown compat, or a variable name collides under compat="no_conflicts".

Source code in src/pyramids/netcdf/ugrid/dataset.py
@_joins_meshes
def merge(
    self,
    others: UgridDataset | list[UgridDataset],
    *,
    compat: str = "no_conflicts",
) -> UgridDataset:
    """Merge the variables of same-topology datasets into one.

    The mesh counterpart of :meth:`pyramids.netcdf.NetCDF.merge`. Every dataset must sit
    on the same mesh; the union of their variables is returned. A variable name present
    in more than one dataset is a conflict and is refused.

    Args:
        others: One dataset, or a list of them, whose variables join ``self``'s. Under
            the class spelling ``UgridDataset.merge([a, b, c])`` this one argument is the
            whole join: its first element becomes ``self`` and the rest are merged onto it.
        compat: How to handle a variable name present in more than one dataset --
            ``"no_conflicts"`` refuses the collision, ``"override"`` keeps the value from
            the **first dataset in join order that carries the name**: ``self``, then each
            of ``others`` in turn. That is ``self``'s only when ``self`` has the variable;
            when it does not, the first of ``others`` carrying it wins. (Under the class
            spelling ``UgridDataset.merge([a, b, c])``, ``self`` is ``a``.) Defaults to
            ``"no_conflicts"``.

    Returns:
        UgridDataset: A new dataset carrying every variable.

    Raises:
        AlignmentError: A dataset sits on a different mesh.
        ValueError: An unknown ``compat``, or a variable name collides under
            ``compat="no_conflicts"``.
    """
    if compat not in ("no_conflicts", "override"):
        raise ValueError(
            f"merge: compat must be 'no_conflicts' or 'override', got {compat!r}."
        )
    parts = [others] if isinstance(others, UgridDataset) else list(others)
    new_vars: dict[str, MeshVariable] = dict(self._data_variables)
    for other in parts:
        self._assert_same_topology(other, "merge")
        for name, var in other._data_variables.items():
            if name in new_vars:
                if compat == "no_conflicts":
                    raise ValueError(
                        f"merge: variable {name!r} is present in more than one dataset; "
                        "rename it first, or pass compat='override'."
                    )
                # compat="override": the first dataset that carries the name wins, which
                # is what already sits in new_vars, so the duplicate is simply skipped.
                continue
            new_vars[name] = var
    return self._rebuild(new_vars)

plot(variable_name, ax=None, cmap='viridis', title=None, basemap=None, colorbar=None, points=None, kind='auto', color=None, contour=None, data_style=None, **kwargs) #

Plot a mesh data variable.

N-6 — this facade now goes through the same module-level helper as the raster path. The mesh-specific dispatch lives in :func:pyramids.dataset._plot_helpers.mesh_render; both Dataset.plot/NetCDF.plot and UgridDataset.plot share the "resolve data, hand to a single helper" contract so the two formats no longer maintain independent plotting code paths.

Parameters:

Name Type Description Default
variable_name str

Name of the data variable to plot.

required
ax Any

matplotlib Axes. Created if None.

None
cmap str

Colormap name.

'viridis'
title str | None

Plot title. Defaults to variable name.

None
basemap bool | str | None

If True, add an OpenStreetMap basemap. If a string, use it as the tile provider name (e.g. "CartoDB.Positron"). Default is None (no basemap). Requires the [viz] extra.

None
colorbar bool or ColorBar

Colour-bar spec, part of the shared plot signature. A pyramids.plot.ColorBar(label=…, …) configures the bar; False hides it and None (default) uses cleopatra's default (a bar is drawn). Only forwarded when set.

None
points ndarray or PointOverlay

Accepted for signature symmetry with the raster plot family, but a no-op here — a mesh has no point-overlay layer (the mesh geometry is the data). Ignored.

None
kind str

Accepted for signature symmetry with the raster plot family, but a no-op here — kind selects a raster renderer (imshow/pcolormesh); the mesh always renders via tripcolor/tricontour. Ignored.

'auto'
color ColorScaling

Colour-scale spec pyramids.plot.ColorScaling (linear / power / sym-log / boundary / midpoint norm), e.g. ColorScaling.power(gamma=0.7). Default None.

None
contour Contour

Contour-line spec pyramids.plot.Contour(levels=…, label_kw=…). Default None.

None
data_style DataStyle

Data-style / relief spec pyramids.plot.DataStyle(style=…, hillshade=…). (A mesh has no cell-value overlay, so there is no cells param here.) Default None.

None
**kwargs Any

Additional arguments passed to mesh_render (forwarded to plot_mesh_data). Notably colorbar (bool, default True): pass colorbar=False to suppress the per-mesh colorbar when you want to attach a custom or shared one to glyph.ax. Also style (name of a cleopatra DATA_STYLES preset, e.g. "flow_accumulation") and hillshade (True or a params dict) to colour / relief- shade the mesh; both require cleopatra >= 0.24 (hillshade needs node-centered data). Distinct from :meth:pyramids.dataset.Dataset.hillshade, which returns a shaded-relief array.

{}

Returns:

Type Description
Any

cleopatra.glyphs.gridded.mesh_glyph.MeshGlyph instance with the plot rendered. Use the returned object to access the matplotlib handles and the mappable:

  • glyph.fig / glyph.ax — Figure and Axes.
  • glyph.im — the mesh mappable (the tripcolor/tricontour(f) artist) set by plot(); use it for a custom colorbar or glyph.im.set_clim(...). It is None after :meth:plot_outline (an outline carries no scalar mapping).
  • glyph.apply_style(style) (cleopatra >= 0.25) — re-apply a DATA_STYLES preset by name in place, without re-plotting.

Raises:

Type Description
ValueError

If the selected variable has no loaded data, or if basemap is requested while the dataset has no CRS (epsg).

Source code in src/pyramids/netcdf/ugrid/dataset.py
def plot(
    self,
    variable_name: str,
    ax: Any = None,
    cmap: str = "viridis",
    title: str | None = None,
    basemap: bool | str | None = None,
    colorbar: bool | ColorBar | None = None,
    points: np.ndarray | PointOverlay | None = None,
    kind: str = "auto",
    color: ColorScaling | None = None,
    contour: Contour | None = None,
    data_style: DataStyle | None = None,
    **kwargs: Any,
) -> Any:
    """Plot a mesh data variable.

    N-6 — this facade now goes through the same module-level
    helper as the raster path. The mesh-specific dispatch lives in
    :func:`pyramids.dataset._plot_helpers.mesh_render`; both
    ``Dataset.plot``/``NetCDF.plot`` and ``UgridDataset.plot`` share
    the "resolve data, hand to a single helper" contract so the
    two formats no longer maintain independent plotting code paths.

    Args:
        variable_name: Name of the data variable to plot.
        ax: matplotlib Axes. Created if None.
        cmap: Colormap name.
        title: Plot title. Defaults to variable name.
        basemap: If True, add an OpenStreetMap basemap. If a string,
            use it as the tile provider name (e.g. "CartoDB.Positron").
            Default is None (no basemap). Requires the [viz] extra.
        colorbar (bool or ColorBar, optional): Colour-bar spec, part of the
            shared plot signature. A ``pyramids.plot.ColorBar(label=…, …)``
            configures the bar; ``False`` hides it and ``None`` (default) uses
            cleopatra's default (a bar is drawn). Only forwarded when set.
        points (np.ndarray or PointOverlay, optional): Accepted for signature
            symmetry with the raster plot family, but a **no-op here** — a mesh
            has no point-overlay layer (the mesh geometry is the data). Ignored.
        kind (str, optional): Accepted for signature symmetry with the raster
            plot family, but a **no-op here** — ``kind`` selects a raster
            renderer (``imshow``/``pcolormesh``); the mesh always renders via
            ``tripcolor``/``tricontour``. Ignored.
        color (ColorScaling, optional): Colour-scale spec
            ``pyramids.plot.ColorScaling`` (linear / power / sym-log / boundary /
            midpoint norm), e.g. ``ColorScaling.power(gamma=0.7)``. Default ``None``.
        contour (Contour, optional): Contour-line spec
            ``pyramids.plot.Contour(levels=…, label_kw=…)``. Default ``None``.
        data_style (DataStyle, optional): Data-style / relief spec
            ``pyramids.plot.DataStyle(style=…, hillshade=…)``. (A mesh has no
            cell-value overlay, so there is no ``cells`` param here.) Default ``None``.
        **kwargs: Additional arguments passed to mesh_render
            (forwarded to plot_mesh_data). Notably ``colorbar``
            (``bool``, default ``True``): pass ``colorbar=False`` to
            suppress the per-mesh colorbar when you want to attach a
            custom or shared one to ``glyph.ax``. Also ``style`` (name of
            a cleopatra ``DATA_STYLES`` preset, e.g. ``"flow_accumulation"``)
            and ``hillshade`` (``True`` or a params dict) to colour / relief-
            shade the mesh; both require cleopatra >= 0.24 (``hillshade``
            needs node-centered data). Distinct from
            :meth:`pyramids.dataset.Dataset.hillshade`, which *returns* a
            shaded-relief array.

    Returns:
        cleopatra.glyphs.gridded.mesh_glyph.MeshGlyph instance with the plot
            rendered. Use the returned object to access the matplotlib
            handles and the mappable:

            - ``glyph.fig`` / ``glyph.ax`` — Figure and Axes.
            - ``glyph.im`` — the mesh mappable (the
              ``tripcolor``/``tricontour(f)`` artist) set by ``plot()``;
              use it for a custom colorbar or ``glyph.im.set_clim(...)``.
              It is ``None`` after :meth:`plot_outline` (an outline
              carries no scalar mapping).
            - ``glyph.apply_style(style)`` (cleopatra >= 0.25) — re-apply a
              ``DATA_STYLES`` preset by name in place, without re-plotting.

    Raises:
        ValueError: If the selected variable has no loaded data, or if
            `basemap` is requested while the dataset has no CRS (`epsg`).
    """
    var = self.get_data(variable_name)
    data = var.data
    if data is None:
        raise ValueError(f"Variable {variable_name!r} has no loaded data to plot.")
    if var.has_time:
        # First step along the variable's own time axis (see `_element_values`).
        data = np.take(np.asarray(data), 0, axis=cast("int", var.time_index))
    if title is None:
        title = variable_name
    if basemap and self.epsg is None:
        raise ValueError("UgridDataset must have a CRS (epsg) to use basemap.")
    # ``points`` / ``kind`` are part of the shared raster-family plot signature
    # but have no meaning for a mesh (no point overlay; the renderer is fixed to
    # tripcolor/tricontour), so they are accepted and ignored. ``colorbar`` and the
    # typed render groups (``color`` / ``contour`` / ``data_style``) map onto the mesh
    # backend and are forwarded only when set (so cleopatra's backend defaults are
    # preserved otherwise).
    if colorbar is not None:
        kwargs["colorbar"] = colorbar
    kwargs.update(
        _nonnull_group_kwargs(color=color, contour=contour, data_style=data_style)
    )
    result = _mesh_render(
        mesh=self._mesh,
        data=data,
        location=var.location,
        ax=ax,
        cmap=cmap,
        title=title,
        basemap=basemap,
        basemap_epsg=self.epsg,
        **kwargs,
    )
    return result

animate(variable_name=None, *, interval=200, **kwargs) #

Animate a temporal mesh variable over its time axis (issue #1380).

The mesh had no animation at all, although a mesh time series is one of the most natural things to animate — a flood propagating across an unstructured grid. The frames come from cleopatra's :meth:MeshGlyph.animate, so this is wiring rather than new drawing code: the topology stays fixed and each step is drawn on it in turn.

Parameters:

Name Type Description Default
variable_name str | None

Variable to animate (default: the only temporal one).

None
interval int

Milliseconds between frames. Defaults to 200.

200
**kwargs Any

Forwarded to cleopatra's MeshGlyph.animate — colorbar, color, contour, data_style, edgecolor, text_loc, …

{}

Returns:

Name Type Description
Any

matplotlib.animation.FuncAnimation: The animation — save it with

Any

anim.save("out.gif"). Note this differs from :meth:Dataset.animate and

Any

meth:NetCDF.animate, which return a glyph whose anim attribute holds the

animation Any

cleopatra's mesh and array glyph families return different objects and

Any

pyramids passes each through rather than wrapping one to look like the other.

Any

Keep a reference to it — matplotlib warns and stops an animation that is only

Any

a temporary, so anim = ds.animate() plays where a bare ds.animate() may

Any

not.

Raises:

Type Description
ValueError

The variable has no time dimension (there would be one frame), or it has a dimension besides time and the elements — a layered variable needs a layer picked before it can be drawn.

See Also

plot: A single frame. Dataset.animate: The raster counterpart, over bands.

Examples:

  • Animate a water-depth series and save it:
    >>> anim = ds.animate("mesh2d_waterdepth", interval=120)  # doctest: +SKIP
    >>> anim.save("depth.gif")  # doctest: +SKIP
    
Source code in src/pyramids/netcdf/ugrid/dataset.py
def animate(
    self,
    variable_name: str | None = None,
    *,
    interval: int = 200,
    **kwargs: Any,
) -> Any:
    """Animate a temporal mesh variable over its time axis (issue #1380).

    The mesh had no animation at all, although a mesh time series is one of the most
    natural things to animate — a flood propagating across an unstructured grid. The
    frames come from cleopatra's :meth:`MeshGlyph.animate`, so this is wiring rather than
    new drawing code: the topology stays fixed and each step is drawn on it in turn.

    Args:
        variable_name: Variable to animate (default: the only temporal one).
        interval: Milliseconds between frames. Defaults to 200.
        **kwargs: Forwarded to cleopatra's ``MeshGlyph.animate`` — ``colorbar``, ``color``,
            ``contour``, ``data_style``, ``edgecolor``, ``text_loc``, …

    Returns:
        matplotlib.animation.FuncAnimation: The animation — save it with
        ``anim.save("out.gif")``. Note this differs from :meth:`Dataset.animate` and
        :meth:`NetCDF.animate`, which return a glyph whose ``anim`` attribute holds the
        animation: cleopatra's mesh and array glyph families return different objects and
        pyramids passes each through rather than wrapping one to look like the other.
        **Keep a reference to it** — matplotlib warns and stops an animation that is only
        a temporary, so ``anim = ds.animate()`` plays where a bare ``ds.animate()`` may
        not.

    Raises:
        ValueError: The variable has no time dimension (there would be one frame), or it
            has a dimension besides time and the elements — a layered variable needs a
            layer picked before it can be drawn.

    See Also:
        plot: A single frame.
        Dataset.animate: The raster counterpart, over bands.

    Examples:
        - Animate a water-depth series and save it:
            ```python
            >>> anim = ds.animate("mesh2d_waterdepth", interval=120)  # doctest: +SKIP
            >>> anim.save("depth.gif")  # doctest: +SKIP
            ```
    """
    var = self._facade_variable("animate", variable_name)
    if not var.has_time:
        raise ValueError(
            f"animate() needs a time axis, but {var.name!r} has none — there would be a "
            f"single frame. Use plot() for a static variable."
        )
    data = np.asarray(var.data)
    axis = cast("int", var.time_index)
    frames = np.moveaxis(data, axis, 0)
    if frames.ndim != 2:
        raise ValueError(
            f"animate() draws one value per element per frame, but {var.name!r} has "
            f"shape {data.shape} — a dimension besides time and the elements. Select a "
            f"layer first, e.g. with isel(layer=0) or collapse_layer()."
        )
    # The variable's own coordinate, not the dataset's: `self.time_values` is the FIRST
    # temporal variable's, so animating a second one of a different length failed inside
    # cleopatra ("time length (3) does not match frame count (6)"). Every other along-time
    # member moved onto this helper in 2c8a308; `animate` was missed.
    labels = _variable_time_coord(var)
    return _ugrid_plot.animate_mesh_data(
        self._mesh,
        frames,
        labels,
        location=var.location,
        interval=interval,
        **kwargs,
    )

plot_outline(ax=None, basemap=None, **kwargs) #

Plot mesh wireframe.

Parameters:

Name Type Description Default
ax Any

matplotlib Axes. Created if None.

None
basemap bool | str | None

True or a web-tile provider name, drawing a tile backdrop under the wireframe — the same backdrop :meth:plot draws under a filled mesh. None (default) draws none. The dataset's own epsg supplies the CRS unless basemap_epsg is passed explicitly, so a mesh with no CRS raises rather than mis-placing the tiles (issue #1354).

None
**kwargs Any

Additional arguments passed to plot_mesh_outline.

{}

Returns:

Type Description
Any

cleopatra.glyphs.gridded.mesh_glyph.MeshGlyph instance with the wireframe rendered. glyph.fig / glyph.ax are the matplotlib handles; glyph.im is None (an outline carries no scalar mapping, so no mappable is produced).

Source code in src/pyramids/netcdf/ugrid/dataset.py
def plot_outline(
    self,
    ax: Any = None,
    basemap: bool | str | None = None,
    **kwargs: Any,
) -> Any:
    """Plot mesh wireframe.

    Args:
        ax: matplotlib Axes. Created if None.
        basemap: ``True`` or a web-tile provider name, drawing a tile backdrop under the
            wireframe — the same backdrop :meth:`plot` draws under a filled mesh. ``None``
            (default) draws none. The dataset's own ``epsg`` supplies the CRS unless
            ``basemap_epsg`` is passed explicitly, so a mesh with no CRS raises rather
            than mis-placing the tiles (issue #1354).
        **kwargs: Additional arguments passed to plot_mesh_outline.

    Returns:
        cleopatra.glyphs.gridded.mesh_glyph.MeshGlyph instance with the wireframe
            rendered. ``glyph.fig`` / ``glyph.ax`` are the matplotlib
            handles; ``glyph.im`` is ``None`` (an outline carries no
            scalar mapping, so no mappable is produced).
    """
    # `basemap_epsg` is a documented parameter of `plot_mesh_outline`, so passing it
    # here used to collide with the dataset's own CRS ("got multiple values for keyword
    # argument"). An explicit one wins; otherwise the dataset's CRS supplies it.
    kwargs.setdefault("basemap_epsg", self.epsg)
    result = _ugrid_plot.plot_mesh_outline(
        self._mesh,
        ax=ax,
        basemap=basemap,
        **kwargs,
    )
    return result

__str__() #

Human-readable summary of the dataset.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def __str__(self) -> str:
    """Human-readable summary of the dataset."""
    lines = [
        f"UgridDataset: {self._file_name or '(in-memory)'}",
        f"  Mesh: {self.mesh_name}",
        f"  Nodes: {self.n_node}, Faces: {self.n_face}, Edges: {self.n_edge}",
        f"  Bounds: {self.bounds}",
        # A mesh may carry a projected WKT with no EPSG code; reporting
        # 'unknown' for a CRS it plainly has was misleading.
        f"  CRS: {self.epsg or (self.crs.name if self.crs is not None else 'unknown')}",
        f"  Data variables ({len(self._data_variables)}):",
    ]
    for name, var in self._data_variables.items():
        lines.append(f"    {name}: location={var.location}, shape={var.shape}")
    result = "\n".join(lines)
    return result

__repr__() #

Repr string for the dataset.

Source code in src/pyramids/netcdf/ugrid/dataset.py
def __repr__(self) -> str:
    """Repr string for the dataset."""
    result = (
        f"UgridDataset(mesh='{self.mesh_name}', "
        f"n_node={self.n_node}, n_face={self.n_face}, n_edge={self.n_edge}, "
        f"variables={self.data_variable_names})"
    )
    return result