File size: 119,750 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 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 | diff --git a/docs/_static/heatwave_widget.js b/docs/_static/heatwave_widget.js
new file mode 100644
index 0000000000000000000000000000000000000000..be9ddbd38ed3db97f5704f8b986a517b371bc3ec
--- /dev/null
+++ b/docs/_static/heatwave_widget.js
@@ -0,0 +1,367 @@
+/*
+ * Interactive Heatwave Definition Explorer
+ * ----------------------------------------
+ * Self-contained, dependency-free widget for the HDP documentation.
+ *
+ * `indexHeatwaves` below is a faithful JavaScript port of HDP's
+ * `index_heatwaves` kernel (the source of truth is hdp/metric.py).
+ * It classifies a 0/1 "hot day" timeseries into indexed heatwave events
+ * using the definition triple [min_duration, max_break, max_subs].
+ *
+ * The widget renders entirely client-side (no kernel, no network, no CDN)
+ * so it works as static HTML on ReadTheDocs and as a crash-proof live demo.
+ */
+(function () {
+ "use strict";
+
+ // ---------------------------------------------------------------------------
+ // Heatwave classification (port of hdp/metric.py :: index_heatwaves)
+ // ---------------------------------------------------------------------------
+ function indexHeatwaves(hotDays, minDuration, maxBreak, maxSubs) {
+ var n = hotDays.length;
+ // Zero-pad to n + 2 so leading/trailing events are bounded by a diff edge.
+ var ts = new Int32Array(n + 2);
+ for (var i = 0; i < n; i++) {
+ if (hotDays[i]) ts[i + 1] = 1;
+ }
+
+ // Discrete difference of the padded series.
+ var diffTs = new Int32Array(ts.length - 1);
+ for (var j = 0; j < diffTs.length; j++) {
+ diffTs[j] = ts[j + 1] - ts[j];
+ }
+
+ // Indices where the series transitions (rising = 1, falling = -1).
+ var diffIndices = [];
+ for (var k = 0; k < diffTs.length; k++) {
+ if (diffTs[k] !== 0) diffIndices.push(k);
+ }
+
+ var inHeatwave = false;
+ var currentHwIndex = 0;
+ var subEvents = 0;
+ var hwIndices = new Int32Array(diffTs.length);
+
+ for (var m = 0; m < diffIndices.length - 1; m++) {
+ var index = diffIndices[m];
+ var nextIndex = diffIndices[m + 1];
+
+ if (diffTs[index] === 1 && nextIndex - index >= minDuration && !inHeatwave) {
+ currentHwIndex += 1;
+ inHeatwave = true;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else if (diffTs[index] === -1 && nextIndex - index > maxBreak) {
+ inHeatwave = false;
+ } else if (diffTs[index] === 1 && inHeatwave && subEvents < maxSubs) {
+ subEvents += 1;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else if (diffTs[index] === 1 && inHeatwave && subEvents >= maxSubs) {
+ if (nextIndex - index >= minDuration) {
+ currentHwIndex += 1;
+ fill(hwIndices, index, nextIndex, currentHwIndex);
+ } else {
+ inHeatwave = false;
+ }
+ subEvents = 0;
+ }
+ }
+
+ // Drop the trailing pad cell to realign with the input length.
+ return hwIndices.subarray(0, hwIndices.length - 1);
+ }
+
+ function fill(arr, start, end, value) {
+ for (var i = start; i < end; i++) arr[i] = value;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Metrics over the slice (analogous to HWN/HWF/HWD/HWA, whole window)
+ // ---------------------------------------------------------------------------
+ function computeMetrics(hwIndex) {
+ var events = {}; // index -> day count
+ for (var i = 0; i < hwIndex.length; i++) {
+ var v = hwIndex[i];
+ if (v !== 0) events[v] = (events[v] || 0) + 1;
+ }
+ var lengths = Object.keys(events).map(function (key) {
+ return events[key];
+ });
+ var hwn = lengths.length;
+ var hwf = lengths.reduce(function (a, b) {
+ return a + b;
+ }, 0);
+ var hwd = lengths.length ? Math.max.apply(null, lengths) : 0;
+ var hwa = lengths.length ? hwf / lengths.length : 0;
+ return { HWN: hwn, HWF: hwf, HWD: hwd, HWA: hwa };
+ }
+
+ // ---------------------------------------------------------------------------
+ // Deterministic synthetic data: rise-then-fall hump + seeded noise
+ // ---------------------------------------------------------------------------
+ var N_DAYS = 30;
+
+ function mulberry32(seed) {
+ return function () {
+ seed |= 0;
+ seed = (seed + 0x6d2b79f5) | 0;
+ var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ }
+
+ function generateTemps(seed) {
+ var rand = mulberry32(seed);
+ var temps = new Float64Array(N_DAYS);
+ var base = 34;
+ // var amplitude = 12; // peak ~40 degC at the middle of the window
+ for (var i = 0; i < N_DAYS; i++) {
+ // Smooth hump peaking near the center of the two-week window.
+ // var hump = Math.sin((i / (N_DAYS - 1)) * Math.PI);
+ var noise = (rand() - 0.5) * 10.0; // +/- ~1.5 degC
+ temps[i] = base + noise;
+ }
+ return temps;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Canvas rendering helpers
+ // ---------------------------------------------------------------------------
+ var COLORS = {
+ notHot: "#9aa5b1",
+ hot: "#f6a623",
+ heatwave: "#d0021b",
+ line: "#2a6592",
+ threshold: "#444",
+ axis: "#888",
+ grid: "#e3e8ee"
+ };
+
+ var PAD = { left: 48, right: 16, top: 16, bottom: 28 };
+
+ function setupCanvas(canvas) {
+ var ratio = window.devicePixelRatio || 1;
+ var cssWidth = canvas.clientWidth;
+ var cssHeight = canvas.clientHeight;
+ canvas.width = Math.round(cssWidth * ratio);
+ canvas.height = Math.round(cssHeight * ratio);
+ var ctx = canvas.getContext("2d");
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.clearRect(0, 0, cssWidth, cssHeight);
+ return { ctx: ctx, w: cssWidth, h: cssHeight };
+ }
+
+ function xForDay(i, w) {
+ var inner = w - PAD.left - PAD.right;
+ return PAD.left + (inner * i) / (N_DAYS - 1);
+ }
+
+ function drawTempPane(canvas, temps, threshold) {
+ var s = setupCanvas(canvas);
+ var ctx = s.ctx;
+ var yMin = 24;
+ var yMax = 44;
+ var inner = s.h - PAD.top - PAD.bottom;
+ function yFor(t) {
+ return PAD.top + inner * (1 - (t - yMin) / (yMax - yMin));
+ }
+
+ // Gridlines + y-axis labels (degC).
+ ctx.strokeStyle = COLORS.grid;
+ ctx.fillStyle = COLORS.axis;
+ ctx.font = "11px sans-serif";
+ ctx.lineWidth = 1;
+ for (var t = yMin; t <= yMax; t += 5) {
+ var y = yFor(t);
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(s.w - PAD.right, y);
+ ctx.stroke();
+ ctx.fillText(t + "°C", 8, y + 3);
+ }
+
+ // Threshold line.
+ ctx.strokeStyle = COLORS.threshold;
+ ctx.setLineDash([5, 4]);
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, yFor(threshold));
+ ctx.lineTo(s.w - PAD.right, yFor(threshold));
+ ctx.stroke();
+ ctx.setLineDash([]);
+ ctx.fillStyle = COLORS.threshold;
+ ctx.fillText("threshold " + threshold.toFixed(1) + "°C", PAD.left + 4, yFor(threshold) - 5);
+
+ // Temperature line.
+ ctx.strokeStyle = COLORS.line;
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+ for (var i = 0; i < N_DAYS; i++) {
+ var px = xForDay(i, s.w);
+ var py = yFor(temps[i]);
+ if (i === 0) ctx.moveTo(px, py);
+ else ctx.lineTo(px, py);
+ }
+ ctx.stroke();
+
+ // Point markers colored by hot / not-hot.
+ for (var j = 0; j < N_DAYS; j++) {
+ ctx.fillStyle = temps[j] > threshold ? COLORS.hot : COLORS.notHot;
+ ctx.beginPath();
+ ctx.arc(xForDay(j, s.w), yFor(temps[j]), 4, 0, 2 * Math.PI);
+ ctx.fill();
+ }
+
+ drawDayAxis(ctx, s);
+ }
+
+ function drawStepPane(canvas, steps) {
+ var s = setupCanvas(canvas);
+ var ctx = s.ctx;
+ var inner = s.h - PAD.top - PAD.bottom;
+ var levels = [0, 1, 2];
+ function yFor(level) {
+ return PAD.top + inner * (1 - level / 2);
+ }
+
+ // Gridlines + level labels.
+ ctx.strokeStyle = COLORS.grid;
+ ctx.fillStyle = COLORS.axis;
+ ctx.font = "11px sans-serif";
+ var labels = ["0 NH", "1 H", "2 HW"];
+ for (var l = 0; l < levels.length; l++) {
+ var y = yFor(levels[l]);
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(s.w - PAD.right, y);
+ ctx.stroke();
+ ctx.fillText(labels[l], 4, y + 3);
+ }
+
+ // Colored bars per day.
+ var innerW = s.w - PAD.left - PAD.right;
+ var barW = (innerW / N_DAYS) * 0.7;
+ for (var i = 0; i < N_DAYS; i++) {
+ var level = steps[i];
+ var color = level === 2 ? COLORS.heatwave : level === 1 ? COLORS.hot : COLORS.notHot;
+ var cx = xForDay(i, s.w);
+ var top = yFor(level);
+ var bottom = yFor(0);
+ ctx.fillStyle = color;
+ if (level === 0) {
+ // Draw a thin marker at the baseline so "not hot" days stay visible.
+ ctx.fillRect(cx - barW / 2, bottom - 2, barW, 2);
+ } else {
+ ctx.fillRect(cx - barW / 2, top, barW, bottom - top);
+ }
+ }
+
+ drawDayAxis(ctx, s);
+ }
+
+ function drawDayAxis(ctx, s) {
+ ctx.strokeStyle = COLORS.axis;
+ ctx.fillStyle = COLORS.axis;
+ ctx.lineWidth = 1;
+ ctx.font = "11px sans-serif";
+ var y = s.h - PAD.bottom;
+ ctx.beginPath();
+ ctx.moveTo(PAD.left, y);
+ ctx.lineTo(s.w - PAD.right, y);
+ ctx.stroke();
+ for (var i = 0; i < N_DAYS; i++) {
+ var px = xForDay(i, s.w);
+ ctx.fillText(String(i + 1), px - 3, y + 16);
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Widget wiring
+ // ---------------------------------------------------------------------------
+ function initWidget(root) {
+ var els = {
+ tempCanvas: root.querySelector("#hdp-hw-temp"),
+ stepCanvas: root.querySelector("#hdp-hw-step"),
+ threshold: root.querySelector("#hdp-hw-threshold"),
+ minDuration: root.querySelector("#hdp-hw-min-duration"),
+ maxBreak: root.querySelector("#hdp-hw-max-break"),
+ maxSubs: root.querySelector("#hdp-hw-max-subs"),
+ thresholdVal: root.querySelector("#hdp-hw-threshold-val"),
+ minDurationVal: root.querySelector("#hdp-hw-min-duration-val"),
+ maxBreakVal: root.querySelector("#hdp-hw-max-break-val"),
+ maxSubsVal: root.querySelector("#hdp-hw-max-subs-val"),
+ regenerate: root.querySelector("#hdp-hw-regenerate"),
+ metrics: root.querySelector("#hdp-hw-metrics")
+ };
+
+ var seed = 1234;
+ var temps = generateTemps(seed);
+
+ function render() {
+ var threshold = parseFloat(els.threshold.value);
+ var minDuration = parseInt(els.minDuration.value, 10);
+ var maxBreak = parseInt(els.maxBreak.value, 10);
+ var maxSubs = parseInt(els.maxSubs.value, 10);
+
+ els.thresholdVal.textContent = threshold.toFixed(1) + "°C";
+ els.minDurationVal.textContent = minDuration + " day" + (minDuration === 1 ? "" : "s");
+ els.maxBreakVal.textContent = String(maxBreak);
+ els.maxSubsVal.textContent = String(maxSubs);
+
+ var hotDays = new Int32Array(N_DAYS);
+ for (var i = 0; i < N_DAYS; i++) hotDays[i] = temps[i] > threshold ? 1 : 0;
+
+ var hwIndex = indexHeatwaves(hotDays, minDuration, maxBreak, maxSubs);
+ var steps = new Int32Array(N_DAYS);
+ for (var j = 0; j < N_DAYS; j++) {
+ steps[j] = hotDays[j] + (hwIndex[j] > 0 ? 1 : 0);
+ }
+
+ drawTempPane(els.tempCanvas, temps, threshold);
+ drawStepPane(els.stepCanvas, steps);
+
+ var m = computeMetrics(hwIndex);
+ els.metrics.innerHTML =
+ metricCell("HWN", m.HWN, "events") +
+ metricCell("HWF", m.HWF, "heatwave days") +
+ metricCell("HWD", m.HWD, "longest event, days") +
+ metricCell("HWA", m.HWA.toFixed(1), "mean event, days");
+ }
+
+ function metricCell(name, value, desc) {
+ return (
+ '<div class="hdp-hw-metric"><span class="hdp-hw-metric-name">' +
+ name +
+ '</span><span class="hdp-hw-metric-value">' +
+ value +
+ '</span><span class="hdp-hw-metric-desc">' +
+ desc +
+ "</span></div>"
+ );
+ }
+
+ [els.threshold, els.minDuration, els.maxBreak, els.maxSubs].forEach(function (slider) {
+ slider.addEventListener("input", render);
+ });
+
+ els.regenerate.addEventListener("click", function () {
+ seed = (Math.random() * 1e9) | 0;
+ temps = generateTemps(seed);
+ render();
+ });
+
+ window.addEventListener("resize", render);
+ render();
+ }
+
+ function boot() {
+ var root = document.getElementById("hdp-hw-widget");
+ if (!root) return; // No-op on pages without the widget.
+ initWidget(root);
+ }
+
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", boot);
+ } else {
+ boot();
+ }
+})();
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..286eb8ac20003cb2dad8c7cb44bb2020fcd5232d
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,48 @@
+import sys
+import os
+import hdp
+from importlib.metadata import version as _get_version
+
+# Configuration file for the Sphinx documentation builder.
+#
+# For the full list of built-in configuration values, see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Project information -----------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
+
+project = 'HDP'
+copyright = '2026, Cameron Cummins'
+author = 'Cameron Cummins'
+release = _get_version('hdp_python')
+
+# -- General configuration ---------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+
+extensions = [
+ 'sphinx.ext.duration',
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.autosummary',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.intersphinx'
+]
+
+intersphinx_mapping = {
+ 'python': ('https://docs.python.org/3', None),
+ 'numpy': ('https://numpy.org/doc/stable', None),
+ 'xarray': ('https://docs.xarray.dev/en/stable', None),
+ 'dask': ('https://docs.dask.org/en/stable', None),
+}
+
+templates_path = ['_templates']
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.ipynb_checkpoints']
+
+
+
+# -- Options for HTML output -------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
+
+html_theme = 'sphinx_rtd_theme'
+html_static_path = ['_static']
+html_js_files = ['heatwave_widget.js']
+html_css_files = ['heatwave_widget.css']
diff --git a/docs/example_cmip_workflow/run_cmip_workflow.py b/docs/example_cmip_workflow/run_cmip_workflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc1188d344f0cc55a05105425b506f8654572524
--- /dev/null
+++ b/docs/example_cmip_workflow/run_cmip_workflow.py
@@ -0,0 +1,53 @@
+import matplotlib
+matplotlib.use('Agg') # Non-interactive backend
+
+from dask.distributed import Client, LocalCluster
+import hdp.measure
+import hdp.threshold
+import hdp.metric
+from hdp.graphics.notebook import create_notebook
+import xarray as xr
+import numpy as np
+import pandas as pd
+import s3fs
+
+
+if __name__ == "__main__":
+ aws_cmip_index = pd.read_csv("https://cmip6-pds.s3.amazonaws.com/pangeo-cmip6.csv")
+ cesm_index = aws_cmip_index.query("table_id=='day' & source_id=='CESM2'")
+ cesm_index = cesm_index[cesm_index["member_id"] == 'r4i1p1f1']
+
+ ssp370_tas_info = cesm_index.query("experiment_id=='ssp370' & variable_id=='tas'")
+ baseline_tas_info = cesm_index.query("experiment_id=='historical' & variable_id=='tas'")
+
+ cluster = LocalCluster(n_workers=6, memory_limit="16GB", threads_per_worker=2, processes=True)
+ client = Client(cluster)
+
+ fs = s3fs.S3FileSystem(anon=True)
+
+ ssp370_tas = xr.open_zarr(fs.get_mapper(ssp370_tas_info["zstore"].iloc[0]), consolidated=True)["tas"]
+ baseline_tas = xr.open_zarr(fs.get_mapper(baseline_tas_info["zstore"].iloc[0]), consolidated=True)["tas"]
+
+ ssp370_tas = ssp370_tas.chunk(dict(time=-1, lat=24, lon=18))
+ baseline_tas = baseline_tas.chunk(dict(time=-1, lat=24, lon=18)).sel(time=slice("1961-01-01", "1990-12-31"))
+
+ baseline_measures = hdp.measure.format_standard_measures(temp_datasets=[baseline_tas])
+ ssp370_measures = hdp.measure.format_standard_measures(temp_datasets=[ssp370_tas])
+
+ percentiles = np.arange(0.9, 1.0, 0.01)
+ thresholds = hdp.threshold.compute_thresholds(
+ baseline_measures,
+ percentiles
+ )
+
+ definitions = [[3,1,0], [3,1,1], [4,0,0], [4,1,1], [5,0,0], [5,1,1]]
+ metrics_dataset = hdp.metric.compute_group_metrics(ssp370_measures, thresholds, definitions)
+
+ metrics_dataset.to_zarr("cesm2_ssp370_hw_metrics.zarr", mode='w', compute=True, zarr_format=2)
+
+ metrics_dataset_disk = xr.open_zarr("cesm2_ssp370_hw_metrics.zarr")
+
+ figure_notebook = create_notebook(metrics_dataset_disk)
+ figure_notebook.save_notebook("cesm2_ssp370_hw_metrics.ipynb")
+
+ client.shutdown()
\ No newline at end of file
diff --git a/docs/sample_data/sample.py b/docs/sample_data/sample.py
new file mode 100644
index 0000000000000000000000000000000000000000..975504e5b0cac5c02b5e4b52e10390828af3825f
--- /dev/null
+++ b/docs/sample_data/sample.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+"""
+hdp.py
+
+Heatwave Diagnostics Package (HDP)
+
+Entry point for package.
+
+Developer: Cameron Cummins
+Contact: cameron.cummins@utexas.edu
+"""
+import matplotlib
+matplotlib.use('Agg') # Non-interactive backend
+
+from hdp.graphics.notebook import create_notebook
+from os.path import isdir
+import hdp.measure
+import hdp.threshold
+import hdp.metric
+import numpy as np
+import sys
+
+
+def generate_sample_data(output_dir):
+ if not isdir(output_dir):
+ raise RuntimeError(f"Output directory '{output_dir}' does not exist!")
+
+ sample_control_temp = hdp.utils.generate_test_control_dataarray(add_noise=True)
+ sample_warming_temp = hdp.utils.generate_test_warming_dataarray(add_noise=True)
+
+ baseline_measures = hdp.measure.format_standard_measures(
+ temp_datasets=[sample_control_temp]
+ )
+ test_measures = hdp.measure.format_standard_measures(
+ temp_datasets=[sample_warming_temp]
+ )
+
+ percentiles = np.arange(0.9, 1.0, 0.01)
+
+ thresholds_dataset = hdp.threshold.compute_thresholds(
+ baseline_measures,
+ percentiles
+ )
+
+ definitions = [[3,0,0], [3,1,1], [4,0,0], [4,1,1], [5,0,0], [5,1,1]]
+
+ metrics_dataset = hdp.metric.compute_group_metrics(test_measures, thresholds_dataset, definitions, include_threshold=True)
+ metrics_dataset.to_netcdf(f"{output_dir}/sample_hw_metrics.nc", mode='w')
+
+ figure_notebook = create_notebook(metrics_dataset)
+ figure_notebook.save_notebook(f"{output_dir}/sample_hw_summary_figures.ipynb")
+
+ sample_control_temp = sample_control_temp.to_dataset()
+ sample_control_temp.attrs["description"] = "Mock control temperature dataset generated by HDP for unit testing."
+ sample_control_temp.to_netcdf(f"{output_dir}/sample_control_temp.nc", mode='w')
+
+ sample_warming_temp = sample_warming_temp.to_dataset()
+ sample_warming_temp.attrs["description"] = "Mock temperature dataset with warming trend generated by HDP for unit testing."
+ sample_warming_temp.to_netcdf(f"{output_dir}/sample_warming_temp.nc", mode='w')
+
+if __name__ == "__main__":
+ print("Generating testing data and simulating a full data-to-figure workflow: ")
+ if len(sys.argv) != 2:
+ assert Exception("Please specifiy the path to output sample data and results to.")
+ generate_sample_data(sys.argv[1])
+ print("Done!")
\ No newline at end of file
diff --git a/hdp/__init__.py b/hdp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/hdp/definitions.py b/hdp/definitions.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4fa994d11176495bd0bcc4f823fec4daf3bebf9
--- /dev/null
+++ b/hdp/definitions.py
@@ -0,0 +1,4 @@
+import os
+
+PATH_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
+PATH_MPL_STYLESHEET = f"{PATH_ROOT_DIR}/graphics/hdp.mplstyle"
\ No newline at end of file
diff --git a/hdp/graphics/__init__.py b/hdp/graphics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/hdp/graphics/figure.py b/hdp/graphics/figure.py
new file mode 100644
index 0000000000000000000000000000000000000000..042933e459ba14dc28b7b10b2f1000778eaa42d7
--- /dev/null
+++ b/hdp/graphics/figure.py
@@ -0,0 +1,373 @@
+from matplotlib import pyplot as plt
+from matplotlib.figure import Figure
+from matplotlib.cm import ScalarMappable
+from matplotlib.colors import Normalize
+from matplotlib import cm
+from cartopy.util import add_cyclic_point
+from hdp.definitions import PATH_MPL_STYLESHEET
+from hdp.graphics.winkel_tripel import WinkelTripel
+import cartopy.crs as ccrs
+import numpy as np
+import cftime
+
+
+def compute_weighted_spatial_mean(da):
+ return da.weighted(np.cos(np.deg2rad(da.lat))).mean(dim=["lat", "lon"])
+
+
+def get_decadal_ranges(times):
+ years = [t.year for t in times]
+
+ start_year = int(np.floor(years[0] / 10)*10)
+ end_year = int(np.ceil(years[-1] / 10)*10)
+
+ decadal_ranges = []
+ for period_start_year in np.arange(start_year, end_year, 10):
+ decadal_ranges.append((int(period_start_year), int(period_start_year) + 9))
+ return decadal_ranges
+
+
+def generate_base_figure():
+ plt.style.use(PATH_MPL_STYLESHEET)
+ f = plt.figure()
+ f.suptitle("Figure Title")
+ return f
+
+
+def convert_axis_to_map(ax):
+ ax.xaxis.set_visible(False)
+ ax.yaxis.set_visible(False)
+ ax.spines['top'].set_visible(False)
+ ax.spines['right'].set_visible(False)
+ ax.spines['left'].set_visible(False)
+ ax.spines['bottom'].set_visible(False)
+ ax.grid(False)
+ return ax.figure.add_axes(ax.get_position(), frameon=True, projection=WinkelTripel(), zorder=-1)
+
+
+def add_four_panel(figure):
+ gridspec = figure.add_gridspec(2, 2)
+ ax1 = figure.add_subplot(gridspec[0, 0])
+ ax2 = figure.add_subplot(gridspec[0, 1])
+ ax3 = figure.add_subplot(gridspec[1, 0])
+ ax4 = figure.add_subplot(gridspec[1, 1])
+
+ axes = [ax1, ax2, ax3, ax4]
+
+ for index, ax in enumerate(axes):
+ ax.set_title(f"Axis {index} Title")
+ ax.set_xlabel("X Label (Units)")
+ ax.set_ylabel("Y Label (Units)")
+
+ return axes
+
+
+def get_color_for_value(cbar, value):
+ """
+ Get the color for a specific value from a colorbar.
+ """
+ cmap = cbar.mappable.get_cmap()
+ norm = cbar.mappable.norm
+ return cmap(norm(value))
+
+
+def get_metric_axis_label(metric_name):
+ if metric_name == "HWF":
+ return "Days"
+ elif metric_name == "HWD":
+ return "Days"
+ elif metric_name == "HWN":
+ return "Heatwaves"
+ elif metric_name == "HWA":
+ return "Days"
+ else:
+ return None
+
+
+def add_percentile_colorbar(ax, percentiles):
+ cmap = plt.get_cmap('Reds', len(percentiles))
+ norm = Normalize(vmin=-1, vmax=len(percentiles) - 1)
+ sm = ScalarMappable(cmap=cmap, norm=norm)
+ sm.set_array([])
+
+ cbar = plt.colorbar(sm, ax=ax, ticks=np.arange(len(percentiles)), pad=0.02)
+ cbar.set_label('Percentile', rotation=270, labelpad=8)
+ cbar.set_ticklabels(np.round(percentiles, 3))
+ return cbar
+
+
+def add_definitions_colorbar(ax, definitions):
+ cmap = plt.get_cmap('tab20', len(definitions))
+ norm = Normalize(vmin=0, vmax=len(definitions) - 1)
+ sm = ScalarMappable(cmap=cmap, norm=norm)
+ sm.set_array([])
+
+ cbar = plt.colorbar(sm, ax=ax, ticks=np.arange(len(definitions)), pad=0.02)
+ cbar.set_label('Definition', rotation=270, labelpad=8)
+ cbar.set_ticklabels(definitions)
+ return cbar
+
+
+def add_percentile_colorbar(ax, percentiles):
+ cmap = plt.get_cmap('autumn', len(percentiles))
+ norm = Normalize(vmin=0, vmax=len(percentiles))
+ sm = ScalarMappable(cmap=cmap, norm=norm)
+ sm.set_array([])
+
+ cbar = plt.colorbar(sm, ax=ax, ticks=np.arange(len(percentiles)) + 0.5, pad=0.02)
+ cbar.set_label('Percentile', rotation=270, labelpad=8)
+ cbar.set_ticklabels(np.round(percentiles, 3))
+ return cbar
+
+
+def get_metric_name(metric_da):
+ if len(metric_da.name.split(".")) >= 3:
+ return metric_da.name.split(".")[2]
+ raise ValueError(
+ f"Expected variable name '{metric_da.name}' to follow the "
+ "'{measure}.{threshold}.{metric}' naming convention."
+ )
+
+
+def get_unique_metric_names(hw_ds):
+ unique_metrics = []
+
+ for name in list(hw_ds.data_vars):
+ parsed = name.split(".")
+ if len(parsed) >= 3:
+ if parsed[2] not in unique_metrics:
+ unique_metrics.append(parsed[2])
+ return unique_metrics
+
+
+def plot_map(metric_da, ax, cmap="hot"):
+ cmap_obj = plt.get_cmap(cmap)
+ metric_da = metric_da.transpose(..., "lon")
+
+ cyclic_values, cyclic_lons = add_cyclic_point(metric_da.values, metric_da.lon.values, axis=-1)
+ ax_contour = ax.contourf(cyclic_lons, metric_da.lat.values, cyclic_values, transform=ccrs.PlateCarree(), cmap=cmap_obj)
+ ax.coastlines()
+ return ax_contour
+
+
+def plot_metric_decadal_maps(metric_da):
+ """
+ Multi-figure (4 panels per figure) plotting of decadal means for a particular metric.
+ If an ensemble, set of percentiles, or set of definitions is supplied, the average will be used.
+ Abbreviations include ensemble (ens), percentile (perc), and definition (def).
+
+ :param metric_da: DataArray of the metric (with the metric name) to plot.
+ :type metric_da: xarray.DataArray
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ metric_name = get_metric_name(metric_da)
+
+ prefix = ""
+ if "member" in metric_da.dims:
+ metric_da = metric_da.mean(dim="member")
+ prefix += " Ens."
+ if "percentile" in metric_da.dims:
+ metric_da = metric_da.mean(dim="percentile")
+ prefix += " Perc."
+ if "definition" in metric_da.dims:
+ metric_da = metric_da.mean(dim="definition")
+ prefix += " Def."
+
+ decadal_ranges = get_decadal_ranges(metric_da.time.values)
+ calendar = metric_da.time.values[0].calendar
+ num_figs = int(np.ceil(len(decadal_ranges) / 4))
+
+ figs = []
+
+ for f_index in range(num_figs):
+ fig = generate_base_figure()
+ fig.suptitle(metric_name)
+ axes = add_four_panel(fig)
+
+ for ax_index, ax in enumerate(axes):
+ ax.set_title(None)
+ slice_index = ax_index + f_index * len(axes)
+ if slice_index < len(decadal_ranges):
+ start_year, end_year = decadal_ranges[slice_index]
+ start_ts = cftime.datetime(start_year, 1, 1, calendar=calendar)
+ end_ts = cftime.datetime(end_year, 1, 1, calendar=calendar)
+ slice_da = metric_da.sel(time=slice(start_ts, end_ts))
+
+ if start_year != slice_da.time.values[0].year:
+ start_year = slice_da.time.values[0].year
+ if end_year != slice_da.time.values[-1].year:
+ end_year = slice_da.time.values[-1].year
+ slice_da = slice_da.mean(dim=["time"])
+
+ ax = convert_axis_to_map(ax)
+ ax_contour = plot_map(slice_da, ax)
+ ax_cbar = fig.colorbar(ax_contour, location="bottom", anchor=(0.0, 0.0), pad=0)
+ ax_cbar.set_label(f"{metric_name} ({get_metric_axis_label(metric_name)})")
+ ax.set_title(f"{start_year} to {end_year}{prefix} Mean")
+ else:
+ ax.set_axis_off()
+ plt.close(fig)
+ figs.append(fig)
+ return figs
+
+
+def plot_metric_timeseries(metric_da):
+ """
+ 4-panel plot of time-evolution of metric, spatial-ensemble mean.
+ The top two panels are means taken across thresholds and definitions while the bottom two panels show standard deviations.
+ Abbreviations include ensemble (ens), percentile (perc), definition (def), and standard deviation (std).
+
+ :param metric_da: DataArray of the metric (with the metric name) to plot.
+ :type metric_da: xarray.DataArray
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ fig = generate_base_figure()
+ axes = add_four_panel(fig)
+
+ spatial_mean = compute_weighted_spatial_mean(metric_da).compute()
+ metric_name = spatial_mean.name.split(".")[2]
+ years = [ts.year for ts in spatial_mean.time.values]
+
+ if "member" in spatial_mean.dims:
+ spatial_mean = spatial_mean.mean(dim="member")
+ axes[0].set_title(f"{metric_name}, Spatial-Ens-Perc. Mean")
+ axes[1].set_title(f"{metric_name}, Spatial-Ens-Def. Mean")
+ axes[2].set_title(f"{metric_name}, Spatial-Ens-Perc. Std.")
+ axes[3].set_title(f"{metric_name}, Spatial-Ens-Def. Std.")
+ else:
+ axes[0].set_title(f"{metric_name}, Spatial-Perc. Mean")
+ axes[1].set_title(f"{metric_name}, Spatial-Def. Mean")
+ axes[2].set_title(f"{metric_name}, Spatial-Perc. Std.")
+ axes[3].set_title(f"{metric_name}, Spatial-Def. Std.")
+
+ def_cbar = add_definitions_colorbar(axes[0], spatial_mean.definition.values)
+ def_cbar = add_definitions_colorbar(axes[2], spatial_mean.definition.values)
+
+ perc_cbar = add_percentile_colorbar(axes[1], spatial_mean.percentile.values)
+ perc_cbar = add_percentile_colorbar(axes[3], spatial_mean.percentile.values)
+
+ for index, definition in enumerate(spatial_mean.definition.values):
+ color = get_color_for_value(def_cbar, index)
+ axes[0].plot(years, spatial_mean.sel(definition=definition).mean(dim="percentile").values, color=color)
+ axes[2].plot(years, spatial_mean.sel(definition=definition).std(dim="percentile").values, color=color)
+
+ for index, percentile in enumerate(spatial_mean.percentile.values):
+ color = get_color_for_value(perc_cbar, index)
+ axes[1].plot(years, spatial_mean.sel(percentile=percentile).mean(dim="definition").values, color=color)
+ axes[3].plot(years, spatial_mean.sel(percentile=percentile).std(dim="definition").values, color=color)
+
+ for ax in axes:
+ ax.set_xlabel("Time (Year)")
+ ax.set_ylabel(f"{metric_name} ({get_metric_axis_label(metric_name)})", labelpad=0.005)
+ ax.set_xlim(years[0], years[-1])
+
+ fig.suptitle(spatial_mean.name)
+ plt.close(fig)
+ return fig
+
+
+def plot_metric_parameter_comparison(metric_da):
+ """
+ 4-panel plot of metric visualizing various comparisons of percentiles against the definitions.
+ If ensemble is supplied, the average is taken.
+
+ :param metric_da: DataArray of the metric (with the metric name) to plot.
+ :type metric_da: xarray.DataArray
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ fig = generate_base_figure()
+ axes = add_four_panel(fig)
+
+ metric_name = get_metric_name(metric_da)
+ fig.suptitle(metric_name)
+
+ if "member" in metric_da.dims:
+ metric_da = metric_da.mean(dim="member")
+
+ spatio_temporal_mean = compute_weighted_spatial_mean(metric_da).mean(dim="time")
+
+ colormesh = axes[0].pcolormesh(spatio_temporal_mean.values, cmap="hot")
+ axes[0].set_xticks(np.arange(spatio_temporal_mean.definition.size) + 0.5)
+ axes[0].set_yticks(np.arange(spatio_temporal_mean.percentile.size) + 0.5)
+ axes[0].set_xticklabels(spatio_temporal_mean.definition.values)
+ axes[0].set_yticklabels(np.round(spatio_temporal_mean.percentile.values, 3))
+ axes[0].set_xlabel("Definition")
+ axes[0].set_ylabel("Percentile")
+ cbar = fig.colorbar(colormesh, ax=axes[0], pad=0.02)
+ cbar.set_label(get_metric_axis_label(metric_name), rotation=270, labelpad=12)
+ axes[0].set_title(f"{metric_name} Spatial-Temporal Mean")
+
+ lon_def_temporal_mean = metric_da.mean(dim=["time", "lon", "definition"])
+ perc_cbar = add_percentile_colorbar(axes[1], lon_def_temporal_mean.percentile.values)
+
+ for index, percentile in enumerate(lon_def_temporal_mean.percentile.values):
+ color = get_color_for_value(perc_cbar, index)
+ axes[1].plot(lon_def_temporal_mean.lat.values, lon_def_temporal_mean.sel(percentile=percentile).values, color=color)
+ axes[1].set_xticks(np.arange(-90, 100, 30))
+ axes[1].set_xlim(-90, 90)
+ axes[1].set_ylabel(get_metric_axis_label(metric_name))
+ axes[1].set_xlabel("Latitude")
+ axes[1].set_title(f"{metric_name} Zonal-Temporal-Def. Means")
+
+ param_mean = metric_da.mean(dim=["time", "percentile", "definition"])
+ axes[2].set_title(None)
+ axes[2] = convert_axis_to_map(axes[2])
+ ax_contour = plot_map(param_mean, axes[2])
+ ax_cbar = fig.colorbar(ax_contour, location="bottom", anchor=(0.0, 0.0), pad=0)
+ ax_cbar.set_label(f"{metric_name} ({get_metric_axis_label(metric_name)})")
+ axes[2].set_title(f"{metric_name} Temporal-Def.-Perc. Mean")
+
+ param_std = metric_da.mean(dim=["time"]).std(dim=["percentile", "definition"])
+ axes[3].set_title(None)
+ axes[3] = convert_axis_to_map(axes[3])
+ ax_contour = plot_map(param_std, axes[3])
+ ax_cbar = fig.colorbar(ax_contour, location="bottom", anchor=(0.0, 0.0), pad=0)
+ ax_cbar.set_label(f"{metric_name} ({get_metric_axis_label(metric_name)})")
+ axes[3].set_title(f"{metric_name} Def.-Perc. Std. of Temporal Mean")
+
+ plt.close(fig)
+ return fig
+
+
+def plot_multi_measure_metric_comparisons(hw_ds):
+ """
+ 4-panel plot of time-evolution of heatwave metrics accross multiple measures.
+ Spatially-weighted by latitide, mean taken spatially and over both percentiles and all definitions.
+ If ensemble is used, the range of member values is shaded behind the mean line.
+ Abbreviations include percentile (perc) and definition (def).
+
+ :param metric_da: Dataset of the metrics (with the metric names) to plot.
+ :type metric_da: xarray.Dataset
+ :return: Matplotlib Figure of the plot with the figure title containing a list of metrics displayed.
+ :rtype: np.ndarray
+ """
+ fig = generate_base_figure()
+ axes = add_four_panel(fig)
+ years = [ts.year for ts in hw_ds.time.values]
+ metric_names = get_unique_metric_names(hw_ds)[:4]
+ fig.suptitle(metric_names)
+
+ for index, metric_name in enumerate(metric_names):
+ metrics = [name for name in hw_ds.data_vars if metric_name in name]
+ metrics_ds = compute_weighted_spatial_mean(hw_ds[metrics]).mean(dim=["percentile", "definition"]).compute()
+
+ axes[index].spines['top'].set_visible(False)
+ axes[index].spines['right'].set_visible(False)
+ axes[index].grid(True)
+
+ axes[index].set_xlabel("Time (Year)")
+ axes[index].set_ylabel(f"{metric_name} ({get_metric_axis_label(metric_name)})", labelpad=2)
+ axes[index].set_xlim(years[0], years[-1])
+ axes[index].set_title(f"{metric_name} Spatial-Perc-Def Mean")
+
+ for metric in metrics_ds:
+ axes[index].plot(years, metrics_ds[metric].values, label=metric.split(".")[0])
+
+ axes[index].legend()
+
+ plt.close(fig)
+ return fig
+
diff --git a/hdp/graphics/notebook.py b/hdp/graphics/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..35b1bb999084b851743e104f3861fa64ba8e98cb
--- /dev/null
+++ b/hdp/graphics/notebook.py
@@ -0,0 +1,146 @@
+import matplotlib.pyplot as plt
+import base64
+import nbformat
+from io import BytesIO
+from datetime import datetime
+from hdp.utils import get_func_description
+from hdp.graphics.figure import *
+from tqdm.auto import tqdm
+
+
+class HDPNotebook():
+ def create_section(self, section_name, label=None, rank=1, label_hidden=False):
+ if label_hidden:
+ label = None
+ elif label is None:
+ label = section_name
+
+ self.__sections[section_name] = {
+ "cells": [],
+ "rank": rank,
+ "label": label
+ }
+
+
+ def __init__(self):
+ self.__sections = {}
+ self.__num_figs = 0
+
+
+ def add_markdown_cell(self, cell_data, section_name):
+ if section_name not in self.__sections:
+ self.create_section(section_name)
+ self.__sections[section_name]["cells"].append(nbformat.v4.new_markdown_cell(cell_data))
+
+
+ def add_figure_cell(self, figure, section_name=None, alt_text="Figure"):
+ img_buffer = BytesIO()
+ figure.savefig(img_buffer, format='png')
+ img_buffer.seek(0)
+
+ img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
+ cell_data = f''
+ img_buffer.close()
+
+ self.add_markdown_cell(cell_data=cell_data, section_name=section_name)
+ self.__num_figs += 1
+
+
+ def set_section_label(section_name, section_label):
+ self.__sections[section_name]["label"] = section_label
+
+
+ def _format_section_label(self, label):
+ return f"## {label}"
+
+
+ def save_notebook(self, path, title=None):
+ from hdp.utils import get_version, get_time_stamp
+ header_data = [
+ '# Heatwave Diagnostics Package (HDP) Standard Figure Deck\n',
+ '' if title is None else f'## Deck Title: {title}\n',
+ '\n',
+ '```\n',
+ 'Webpage: https://github.com/AgentOxygen/HDP\n',
+ f'Version: HDP {get_version()}\n',
+ f'Generation Timestamp: {get_time_stamp()}\n',
+ f'Figures Generated: {self.__num_figs}\n',
+ '```\n'
+ ]
+
+ self.create_section("header", rank=0, label_hidden=True)
+ self.add_markdown_cell(header_data, "header")
+
+ notebook_node = nbformat.v4.new_notebook()
+ ranked_cells = {}
+ for section_name in self.__sections:
+ rank = self.__sections[section_name]["rank"]
+ if rank in ranked_cells:
+ ranked_cells[rank].append(section_name)
+ else:
+ ranked_cells[rank] = [section_name]
+
+ ranks = list(ranked_cells.keys())
+ ranks.sort()
+
+ for rank in ranks:
+ for section_name in ranked_cells[rank]:
+ label = self.__sections[section_name]["label"]
+ if label is not None:
+ label_cell = nbformat.v4.new_markdown_cell(self._format_section_label(label), metadata={"jp-MarkdownHeadingCollapsed": True})
+
+ notebook_node.cells.append(label_cell)
+
+ for cell in self.__sections[section_name]["cells"]:
+ notebook_node.cells.append(cell)
+
+ with open(path, 'w') as nb_file:
+ nbformat.write(notebook_node, nb_file)
+
+
+def create_notebook(hw_ds):
+ assert "hdp_type" in hw_ds.attrs, "Missing 'hdp_type' attribute."
+
+ notebook = HDPNotebook()
+
+ if hw_ds.attrs["hdp_type"] == "measure":
+ pass
+ elif hw_ds.attrs["hdp_type"] == "threshold":
+ pass
+ elif hw_ds.attrs["hdp_type"] == "metric":
+ index = 1
+
+ section_name = f"Figures {index}"
+ notebook.create_section(section_name)
+ desc = get_func_description(plot_multi_measure_metric_comparisons)
+ notebook.add_markdown_cell(f"### Figure {index}.2 \n{desc}", section_name)
+ notebook.add_figure_cell(plot_multi_measure_metric_comparisons(hw_ds), section_name, alt_text=f"{section_name}")
+
+ index += 1
+ # This is fragile and should be improved to use metadata
+ metric_names = [name for name in list(hw_ds.data_vars) if len(name.split(".")) >= 3]
+ for metric in tqdm(metric_names, desc="Generating figures:"):
+ section_name = f"Figures {index}-{metric}"
+
+ notebook.create_section(section_name)
+ notebook.add_markdown_cell("Description of these figures.", section_name)
+
+ desc = get_func_description(plot_metric_parameter_comparison)
+ notebook.add_markdown_cell(f"### Figure {index}.1 \n{desc}", section_name)
+ notebook.add_figure_cell(plot_metric_parameter_comparison(hw_ds[metric]), section_name, alt_text=f"{section_name}")
+
+ desc = get_func_description(plot_metric_timeseries)
+ notebook.add_markdown_cell(f"### Figure {index}.2 \n{desc}", section_name)
+ notebook.add_figure_cell(plot_metric_timeseries(hw_ds[metric]), section_name, alt_text=f"{section_name}")
+
+ iindex = 3
+ for fig in plot_metric_decadal_maps(hw_ds[metric]):
+ desc = get_func_description(plot_metric_decadal_maps)
+ notebook.add_markdown_cell(f"### Figure {index}.{iindex} \n{desc}", section_name)
+ notebook.add_figure_cell(fig, section_name, alt_text=f"{section_name}")
+ iindex += 1
+ index += 1
+ else:
+ raise ValueError(f"Unexpected value for 'hdp_type' attribute, '{hw_ds.attrs["hdp_type"]}' is not 'measure', 'threshold', or 'metric'.")
+
+ return notebook
\ No newline at end of file
diff --git a/hdp/graphics/winkel_tripel.py b/hdp/graphics/winkel_tripel.py
new file mode 100644
index 0000000000000000000000000000000000000000..395f83d8aa1b536d36939a51e837dcf4ce1f27a7
--- /dev/null
+++ b/hdp/graphics/winkel_tripel.py
@@ -0,0 +1,19 @@
+import cartopy.crs as ccrs
+
+
+class WinkelTripel(ccrs._WarpedRectangularProjection):
+ """
+ Winkel-Tripel projection implementation for Cartopy
+ """
+
+ def __init__(self, central_longitude=0.0, central_latitude=0.0, globe=None):
+ globe = globe or ccrs.Globe(semimajor_axis=ccrs.WGS84_SEMIMAJOR_AXIS)
+ proj4_params = [('proj', 'wintri'),
+ ('lon_0', central_longitude),
+ ('lat_0', central_latitude)]
+
+ super(WinkelTripel, self).__init__(proj4_params, central_longitude, globe=globe)
+
+ @property
+ def threshold(self):
+ return 1e4
\ No newline at end of file
diff --git a/hdp/measure.py b/hdp/measure.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a4cf56ba25c3860ff219fb001d0e98efd9c2e4b
--- /dev/null
+++ b/hdp/measure.py
@@ -0,0 +1,203 @@
+import numpy as np
+import numba as nb
+import xarray
+from hdp.utils import add_history, get_version
+
+TEMPERATURE_UNITS = ['degC', 'degK', 'degF', 'C', 'K', 'F']
+HUMIDITY_UNITS = ["%", "g/g"]
+
+
+def kelvin_to_celsius(temp: xarray.DataArray) -> xarray.DataArray:
+ """
+ Converts from temperature value from Kelvin to Celsius.
+
+ :param temp: Temperature DataArray in degrees Kelvin
+ :type temp: xarray.DataArray
+ :return: Temperature DataArray in degrees Celsius
+ :rtype: xarray.DataArray
+ """
+ attrs = temp.attrs
+ temp -= 273.15
+ attrs["units"] = "degC"
+ temp.attrs = attrs
+ temp = add_history(temp, "HDP converted units from Kelvin to Celsius.")
+ return temp
+
+
+def fahrenheit_to_celsius(temp: xarray.DataArray) -> xarray.DataArray:
+ """
+ Converts from temperature value from Fahrenheit to Celsius.
+
+ :param temp: Temperature DataArray in degrees Fahrenheit
+ :type temp: xarray.DataArray
+ :return: Temperature DataArray in degrees Celsius
+ :rtype: xarray.DataArray
+ """
+ attrs = temp.attrs
+ temp = (temp - 32) / 1.8
+ attrs["units"] = "degC"
+ temp.attrs = attrs
+ temp = add_history(temp, "HDP converted units from Fahrenheit to Celsius.")
+ return temp
+
+
+def celsius_to_fahrenheit(temp: xarray.DataArray) -> xarray.DataArray:
+ """
+ Converts from temperature value from Celsius to Fahrenheit.
+
+ :param temp: Temperature DataArray in degrees Celsius
+ :type temp: xarray.DataArray
+ :return: Temperature DataArray in degrees Fahrenheit
+ :rtype: xarray.DataArray
+ """
+ attrs = temp.attrs
+ temp = (temp * 1.8) + 32
+ attrs["units"] = "degF"
+ temp.attrs = attrs
+ temp = add_history(temp, "HDP converted units from Celsius to Fahrenheit.")
+ return temp
+
+
+@nb.vectorize([nb.float32(nb.float32, nb.float32)])
+def heat_index(temp: float, rel_humid: float) -> float:
+ """
+ Calculates heat index from temperature and relative humidity.
+
+ This function relies on a regression of the National Weather Service heat index.
+ It has an error of +/- 1.3 degrees Fahrenheit.
+ https://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
+
+ :param temp: Temperature value in degrees Fahrenheit
+ :type temp: float
+ :param rel_humid: Relative humidity on scale from 0 (no moisture) to 100 (fully saturated).
+ :type rel_humid: float
+ :return: Heat index value in degrees Fahrenheit
+ :rtype: float
+ """
+ hi = 0.5 * (temp + 61.0 + ((temp - 68.0)*1.2) + (rel_humid*0.094))
+ if hi > 80:
+ hi = -42.379
+ hi += 2.04901523*temp
+ hi += 10.14333127*rel_humid
+ hi += -0.22475541*temp*rel_humid
+ hi += -0.00683783*(temp**2)
+ hi += -0.05481717*(rel_humid**2)
+ hi += 0.00122874*(temp**2)*rel_humid
+ hi += 0.00085282*temp*(rel_humid**2)
+ hi += -0.00000199*((rel_humid*temp)**2)
+
+ if rel_humid < 13 and 80 <= temp <= 112:
+ hi -= ((13 - rel_humid)/4)*np.sqrt((np.abs(17 - np.abs(temp - 95))/17))
+ elif rel_humid > 85 and 80 <= temp <= 87:
+ hi += ((rel_humid - 85)/10) * ((87 - temp)/5)
+
+ return hi
+
+
+def heat_index_map_wrapper(ds):
+ hi_da = xarray.apply_ufunc(heat_index,
+ ds["temp"].astype(np.float32),
+ ds["rh"].astype(np.float32),
+ dask="parallelized",
+ input_core_dims=[[], []],
+ output_core_dims=[[]],
+ output_dtypes=[np.float32],
+ dask_gufunc_kwargs={
+ 'allow_rechunk': False
+ })
+ return hi_da
+
+
+def apply_heat_index(temp: xarray.DataArray, rh: xarray.DataArray) -> xarray.DataArray:
+ """
+ Calculates heat index from temperature and relative humidity DataArrays leveraging Dask.
+
+ :param temp: Temperature DataArray in degrees Fahrenheit
+ :type temp: xarray.DataArray
+ :param rh: Relative humidity DataArray in percentage [0-100]
+ :type rh: xarray.DataArray
+ :return: Heat index value in degrees Fahrenheit
+ :rtype: xarray.DataArray
+ """
+ assert temp.attrs["units"] == "degF"
+ assert rh.attrs["units"] == "%"
+ hi_da = heat_index_map_wrapper(
+ xarray.Dataset({
+ "temp": temp,
+ "rh": rh
+ }),
+ )
+ hi_da = hi_da.rename(f"{temp.name}_hi")
+ hi_da.attrs["baseline_variable"] = hi_da.name
+ hi_da = add_history(hi_da, f"Converted to heat index using '{rh.name}' relative humidity, renamed from '{temp.name}' to '{hi_da.name}'.")
+ return hi_da
+
+
+def convert_temp_units(temp_ds: xarray.DataArray) -> xarray.DataArray:
+ """
+ Determines and converts temperature units to degrees Celsius.
+
+ :param temp_ds: Temperature DataArray with one of the supported units
+ :type temp_ds: xarray.DataArray
+ :return: Temperature DataArray in degrees Celsius
+ :rtype: xarray.DataArray
+ """
+ if temp_ds.attrs["units"] == "K" or temp_ds.attrs["units"] == "degK":
+ temp_ds = kelvin_to_celsius(temp_ds)
+ elif temp_ds.attrs["units"] == "F" or temp_ds.attrs["units"] == "degF":
+ temp_ds = fahrenheit_to_celsius(temp_ds)
+ return temp_ds
+
+
+def format_standard_measures(temp_datasets: list[xarray.DataArray], rh: xarray.DataArray = None) -> xarray.Dataset:
+ """
+ Formats heat measure datasets (base inputs for heatwave diagnostics) for use within the HDP.
+
+ :param temp_datasets: List of input temperature DataArrays using supported units
+ :type temp_datasets: list[xarray.DataArray]
+ :param rh: (Optional) Relative humidity DataArray to compute heat index values with for each temperature DataArray.
+ :type rh: xarray.DataArray
+ :return: Dataset containing all input variables formatted and initialized for HDP analysis.
+ :rtype: xarray.Dataset
+ """
+ measures = []
+
+ for temp_ds in temp_datasets:
+ temp_ds = temp_ds.copy(deep=True).astype(np.float32)
+ assert "units" in temp_ds.attrs, f"Attribute 'units' not found in '{temp_ds.name}' dataset."
+ assert temp_ds.attrs["units"] in TEMPERATURE_UNITS, f"Units for '{temp_ds.name}' must be one of the following: {TEMPERATURE_UNITS}"
+ temp_ds.attrs |= {
+ "hdp_type": "measure",
+ "input_variable": temp_ds.name,
+ "baseline_variable": temp_ds.name
+ }
+
+ temp_ds = convert_temp_units(temp_ds)
+ measures.append(temp_ds)
+
+ if rh is not None:
+ rh = rh.copy(deep=True).astype(np.float32)
+ assert "units" in rh.attrs, "Attribute 'units' not found in rh dataset."
+ assert rh.attrs["units"] in HUMIDITY_UNITS, f"Units for rh must be one of the following: {HUMIDITY_UNITS}"
+
+ if rh.attrs["units"] == "g/g":
+ rh *= 100
+ rh.attrs["units"] = "%"
+
+ heat_index_datasets = []
+ for measure in measures:
+ ftemp_ds = celsius_to_fahrenheit(measure.copy(deep=True))
+ heat_index = apply_heat_index(ftemp_ds, rh)
+ heat_index_datasets.append(fahrenheit_to_celsius(heat_index))
+
+ for hi_ds in heat_index_datasets:
+ measures.append(hi_ds)
+
+ agg_ds = xarray.merge(measures, join="outer")
+ agg_ds.attrs = {
+ "description": f"Heat measurement dataset generated by Heatwave Diagnostics Package (HDP v{get_version()})",
+ "hdp_version": get_version(),
+ }
+ agg_ds = add_history(agg_ds, f"Dataset aggregated by HDP with measures: {[ds.name for ds in measures]}")
+
+ return agg_ds
\ No newline at end of file
diff --git a/hdp/metric.py b/hdp/metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..606c88942508bc8e2edfa5e32f72077cf62bb3cd
--- /dev/null
+++ b/hdp/metric.py
@@ -0,0 +1,603 @@
+import xarray
+import numpy as np
+import cftime
+import numba as nb
+import datetime
+from os import makedirs
+from pathlib import Path
+from hdp.utils import get_version, add_history
+from tqdm.auto import tqdm
+import dask.array as da
+
+
+@nb.njit
+def index_heatwaves(hot_days_ts: np.ndarray, min_duration: int, max_break: int, max_subs: int) -> np.ndarray:
+ """
+ Identifies the heatwaves in the timeseries using the specified heatwave definition
+
+ :param hot_days_ts: Integer array of ones and zeros where ones indicates a hot day
+ :type hot_days_ts: np.ndarray
+ :param min_duration: The minimum number of hot days to constitute a heatwave event, including after breaks
+ :type min_duration: int
+ :param max_break: The maximum number of days between hot days within one heatwave event
+ :type max_break: int
+ :param max_subs: the maximum number of subsequent events allowed to be apart of the initial consecutive hot days
+ :type max_subs: int
+ :return: Timeseries where nonzero integers indicate heatwave indices for each timestep
+ :rtype: np.ndarray
+ """
+ ts = np.zeros(hot_days_ts.size + 2, dtype=nb.int64)
+ for i in range(0, hot_days_ts.size):
+ if hot_days_ts[i]:
+ ts[i + 1] = 1
+ diff_ts = np.diff(ts)
+ diff_indices = np.where(diff_ts != 0)[0]
+
+ in_heatwave = False
+ current_hw_index = 0
+ sub_events = 0
+ hw_indices = np.zeros(diff_ts.size, dtype=nb.int64)
+
+ for i in range(diff_indices.size-1):
+ index = diff_indices[i]
+ next_index = diff_indices[i+1]
+
+ if diff_ts[index] == 1 and next_index - index >= min_duration and not in_heatwave:
+ current_hw_index += 1
+ in_heatwave = True
+ hw_indices[index:next_index] = current_hw_index
+ elif diff_ts[index] == -1 and next_index - index > max_break:
+ in_heatwave = False
+ elif diff_ts[index] == 1 and in_heatwave and sub_events < max_subs:
+ sub_events += 1
+ hw_indices[index:next_index] = current_hw_index
+ elif diff_ts[index] == 1 and in_heatwave and sub_events >= max_subs:
+ if next_index - index >= min_duration:
+ current_hw_index += 1
+ hw_indices[index:next_index] = current_hw_index
+ else:
+ in_heatwave = False
+ sub_events = 0
+
+ return hw_indices[0:hw_indices.size-1]
+
+
+@nb.njit
+def heatwave_number(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the number of heatwaves (by event, not days) in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWN.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Number of heatwaves per heatwave season
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.int64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ uniques = np.unique(hw_ts[end_points[0]:end_points[1]])
+ output[y] = uniques[uniques != 0].size
+
+ return output
+
+
+@nb.njit
+def heatwave_frequency(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the number of heatwave days in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWF.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Number of heatwave days per heatwave season.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.int64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ output[y] = np.sum(hw_ts[end_points[0]:end_points[1]] > 0, dtype=nb.int64)
+ return output
+
+
+@nb.njit
+def heatwave_duration(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the length of the longest heatwave in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWD.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Length of longest heatwave per heatwave season.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.int64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ hw_ts_slice = hw_ts[end_points[0]:end_points[1]]
+ unique_indices = np.unique(hw_ts_slice)
+
+ if unique_indices.size == 1:
+ output[y] = 0
+ else:
+ unique_indices = unique_indices[1:]
+
+ hw_lengths = np.zeros(unique_indices.size, dtype=nb.int64)
+ for index, value in enumerate(unique_indices):
+ if value != 0:
+ for day in hw_ts_slice:
+ if day == value:
+ hw_lengths[index] += 1
+
+ output[y] = np.max(hw_lengths)
+ return output
+
+
+@nb.njit
+def heatwave_average(hw_ts: np.ndarray, season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Measures the average length of all heatwaves in each season of a given heatwave index time series.
+ Heatwave metric, commonly abbreviated as HWA.
+
+ :param hw_ts: Integer timeseries of indexed heatwave days.
+ :type hw_ts: np.ndarray
+ :param season_ranges: Range of array indices, corresponding to heatwave season, in indexed heatwave day timeseries to count.
+ :type season_ranges: np.ndarray
+ :return: Average heatwave length per heatwave season.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(season_ranges.shape[0], dtype=nb.float64)
+ for y in range(season_ranges.shape[0]):
+ end_points = season_ranges[y]
+ hw_ts_slice = hw_ts[end_points[0]:end_points[1]]
+ unique_indices = np.unique(hw_ts_slice)
+
+ if unique_indices.size == 1:
+ output[y] = 0
+ else:
+ unique_indices = unique_indices[1:]
+
+ hw_lengths = np.zeros(unique_indices.size, dtype=nb.int64)
+ for index, value in enumerate(unique_indices):
+ if value != 0:
+ for day in hw_ts_slice:
+ if day == value:
+ hw_lengths[index] += 1
+
+ output[y] = np.mean(hw_lengths)
+ return output
+
+
+def get_range_indices(times: np.ndarray, start: tuple, end: tuple) -> np.ndarray:
+ """
+ Calculates the range of time indices to define each heatwave season for a given time series.
+ This function is agnostic to the calendar type, but will not yield accurate results if the month and day exceed the calendar's definition.
+ The ranges of indices are then used to slice the time series into the heatwave seasons, this is faster than iterating through CFTime objects.
+
+ :param times: Array of CFTime objects corresponding to the time series to define the seasons over.
+ :type times: np.ndarray
+ :param start: Tuple of starting month integer and day integer to compare times array against.
+ :type start: tuple
+ :param end: Tuple of ending month integer and day integer to compare times array against.
+ :type end: tuple
+ :return: Range of indices in times array for each season.
+ :rtype: np.ndarray
+ """
+ num_years = times[-1].year - times[0].year + 1
+ ranges = np.zeros((num_years, 2), dtype=int) - 1
+
+ n = 0
+ looking_for_start = True
+ for t in range(times.shape[0]):
+ if looking_for_start:
+ if times[t].month == start[0] and times[t].day == start[1]:
+ looking_for_start = False
+ ranges[n, 0] = t
+ else:
+ if times[t].month == end[0] and times[t].day == end[1]:
+ looking_for_start = True
+ ranges[n, 1] = t
+ n += 1
+
+ if not looking_for_start:
+ ranges[-1, -1] = times.shape[0]
+
+ return ranges
+
+
+def compute_hemisphere_ranges(measure: xarray.DataArray) -> xarray.DataArray:
+ """
+ Computes the heatwave season ranges by time index (not the timestamp, rather the index corresponding to the timestamp) for each grid cell based on whether it is in the Northern Hemisphere (boreal summer, May 1st to October 1st) or Southern Hemisphere (austral summer, November 1st to March 1st).
+
+ :param measure: DataArray containing 'lat' and 'lon' variables corresponding to grid.
+ :type measure: xarray.DataArray
+ :return: Generates seasonal ranges by hemisphere for an arbitrary 'lat'-'lon' grid.
+ :rtype: xarray.DataArray
+ """
+ north_ranges = get_range_indices(measure.time.values, (5, 1), (10, 1))
+ south_ranges = get_range_indices(measure.time.values, (11, 1), (4, 1))
+
+ slice_start = 0
+ slice_end = north_ranges.size
+ start_indentified = False
+ for year_index, n_end_points in enumerate(north_ranges):
+ end_points = np.concatenate([n_end_points, south_ranges[year_index]])
+
+ if -1 in end_points and not start_indentified:
+ slice_start = year_index
+ continue
+ elif not start_indentified:
+ start_indentified = True
+
+ if start_indentified and -1 in end_points:
+ slice_end = year_index
+ break
+
+ north_ranges = north_ranges[slice_start:slice_end]
+ south_ranges = south_ranges[slice_start:slice_end]
+ years = np.arange(measure.time.values[0].year, measure.time.values[-1].year + 1, 1)
+ years = years[slice_start:slice_end]
+
+ ranges = np.zeros((north_ranges.shape[0], 2, measure.lat.size, measure.lon.size), dtype=int) - 1
+
+ for i in range(measure.lat.size):
+ for j in range(measure.lon.size):
+ if measure.lat.values[i] < 0:
+ ranges[:, :, i, j] = south_ranges
+ else:
+ ranges[:, :, i, j] = north_ranges
+
+
+ return xarray.DataArray(data=ranges,
+ dims=["year", "end_points", "lat", "lon"],
+ coords={
+ "year": years,
+ "end_points": ["start", "finish"],
+ "lat": measure.lat.values,
+ "lon": measure.lon.values
+ })
+
+
+def build_doy_map(times: np.ndarray) -> np.ndarray:
+ """
+ Maps the time series index (key) to its respective day of the year (value).
+
+ :param measure: Array of CFTime objects.
+ :type measure: np.ndarray
+ :return: Day of year for each timestep.
+ :rtype: np.ndarray
+ """
+ doy_map = np.zeros(times.size, dtype=int) - 1
+ for time_index, time in enumerate(times):
+ doy_map[time_index] = time.dayofyr - 1
+ return doy_map
+
+
+@nb.njit
+def indicate_hot_days(measure: np.ndarray, threshold: np.ndarray, doy_map: np.ndarray) -> np.ndarray:
+ """
+ Determines whether each time step in a heat measure exceeds the threshold.
+
+ :param measure: Heat measure to compare against the threshold.
+ :type measure: np.ndarray
+ :param threshold: Threshold for extreme heat.
+ :type threshold: np.ndarray
+ :param doy_map: Mapping from index in times array to day of year value.
+ :type doy_map: np.ndarray
+ :return: Boolean array of days in measure that exceed the threshold.
+ :rtype: np.ndarray
+ """
+ output = np.zeros(measure.shape, dtype=nb.boolean)
+ for t in range(measure.size):
+ doy = doy_map[t]
+ if measure[t] > threshold[doy]:
+ output[t] = True
+ else:
+ output[t] = False
+ return output
+
+
+@nb.njit
+def compute_heatwave_metrics(measure: np.ndarray, threshold: np.ndarray, doy_map: np.ndarray,
+ min_duration: int, max_break: int, max_subs: int,
+ season_ranges: np.ndarray) -> np.ndarray:
+ """
+ Computes HWN, HWF, HWD, and HWA metrics for a given measure, threshold, and definition. Additional parameters can be used to fine tune the analysis.
+ This is the Numba-compiled function that is parallelized with Dask and formatted into a more user-friendly format by hdp.metrics.compute_individual_metrics
+
+ :param measure: Heat measure to compare against the threshold.
+ :type measure: np.ndarray
+ :param threshold: Threshold for extreme heat.
+ :type threshold: np.ndarray
+ :param doy_map: Mapping from index in times array to day of year value.
+ :type doy_map: np.ndarray
+ :param min_duration: Minimum number of days that exceed the threshold to constitute a heatwave.
+ :type min_duration: int
+ :param max_break: Maximum number of days below the threshold that can exist in a heatwave.
+ :type max_break: int
+ :param max_subs: Maximum number of subsequent heatwaves.
+ :type max_subs: int
+ :param season_ranges:
+ :type season_ranges: np.ndarray
+ :return: Array of equal number of dimensions to measure and an additional dimension containing each heatwave metric: HWN, HWF, HWD, HWA
+ :rtype: np.ndarray
+ """
+ hot_days_ts = indicate_hot_days(measure, threshold, doy_map)
+ hw_ts = index_heatwaves(hot_days_ts, min_duration, max_break, max_subs)
+ hwf = heatwave_frequency(hw_ts, season_ranges)
+ hwn = heatwave_number(hw_ts, season_ranges)
+ hwd = heatwave_duration(hw_ts, season_ranges)
+ hwa = heatwave_average(hw_ts, season_ranges)
+
+ output = np.zeros((4,) + hwf.shape, dtype=nb.int64)
+ output[0] = hwf
+ output[1] = hwn
+ output[2] = hwd
+ output[3] = hwa
+ return output
+
+
+def compute_heatwave_metrics_wrapper(measure, threshold, doy_map, hw_definitions):
+ season_ranges = compute_hemisphere_ranges(measure)
+
+ def_coords = xarray.DataArray(
+ [f"{hw_def[0]}-{hw_def[1]}-{hw_def[2]}" for hw_def in hw_definitions],
+ dims=["definition"]
+ )
+ perc_coords = xarray.DataArray(
+ threshold.percentile.values,
+ dims=["percentile"]
+ )
+
+ perc_datasets = []
+ for perc in threshold.percentile.values:
+ def_datasets = []
+ for hw_def in hw_definitions:
+ metric_data = xarray.apply_ufunc(compute_heatwave_metrics, measure, threshold.sel(percentile=perc), doy_map,
+ hw_def[0], hw_def[1], hw_def[2],
+ season_ranges,
+ vectorize=True, dask="parallelized",
+ input_core_dims=[["time"], ["doy"], ["time"], [], [], [], ["year", "end_points"]],
+ output_core_dims=[["metric", "year"]],
+ output_dtypes=[int], dask_gufunc_kwargs=dict(output_sizes=dict(metric=4)))
+ def_datasets.append(metric_data)
+ perc_datasets.append(xarray.concat(def_datasets, dim=def_coords))
+ return xarray.concat(perc_datasets, dim=perc_coords)
+
+
+def compute_individual_metrics(measure: xarray.DataArray, threshold: xarray.DataArray, hw_definitions: list, include_threshold: bool=True, check_variables: bool=True) -> xarray.Dataset:
+ """
+ Computes HWN, HWF, HWD, and HWA heatwave metrics for an individual parameter configuration of measure, threshold, and definition.
+
+ Heatwave definitions are described by tuples of three integers in the following order:
+ 1. Minimum number of days exceeding the threshold to define the start of a heatwave
+ 2. Maximum number of days following the start of a heatwave that do not exceed the threshold and are followed by days that do exceed the threshold. In other words, the maximum "break" that a heatwave can have between the initial hot days and some number of hot days afterwards.
+ 3. Maximum number of breaks in a heatwave (can also be thought of as the maximum number of secondary events after the initial hot days).
+
+ :param measure: Formatted HDP measure DataArray
+ :type measure: xarray.DataArray
+ :param threshold: Formatted HDP threshold compatable with the given measure
+ :type threshold: xarray.DataArray
+ :param hw_definitions: Heatwave definitions to calculate metrics for. See the function description for how to generate definitions.
+ :type hw_definitions: list[tuple]
+ :param include_threshold: (Optional) Whether or not to include the threshold DataArray in the aggregated output dataset. Default is True.
+ :type include_threshold: bool
+ :param check_variables: (Optional) Whether or not to check if measure is compatable with the threshold. Default is True.
+ :type check_variables: bool
+ :return: Aggregate dataset containing all of the heatwave metrics and optional datasets.
+ :rtype: xarray.Dataset
+ """
+ if check_variables:
+ assert "hdp_type" in threshold.attrs
+ assert threshold.attrs["hdp_type"] == "threshold"
+ assert threshold.attrs["baseline_variable"] == measure.attrs["baseline_variable"]
+ assert threshold.attrs["baseline_calendar"] == measure.time.values[0].calendar
+
+ combined_history = ""
+ if "history" in measure.attrs:
+ for entry in measure.attrs["history"].split("\n"):
+ if entry != '':
+ combined_history += (f"(Measure) {entry}\n")
+ if "history" in threshold.attrs:
+ for entry in threshold.attrs["history"].split("\n"):
+ if entry != '':
+ combined_history += (f"(Threshold) {entry}\n")
+
+ season_ranges = compute_hemisphere_ranges(measure)
+
+ times = measure.time.values
+ doy_map = xarray.DataArray(
+ data=build_doy_map(times),
+ coords={"time": times}
+ )
+
+ da_dims = ["percentile", "definition"]
+ da_shape = [threshold.percentile.size, len(hw_definitions)]
+ da_chunks = [(threshold.percentile.size), (len(hw_definitions))]
+
+ for index, dim in enumerate(measure.dims):
+ if dim != "time":
+ da_dims.append(dim)
+ da_shape.append(measure.shape[index])
+ da_chunks.append(measure.chunks[index])
+
+ da_dims.extend(["metric", "year"])
+ da_shape.extend([4, season_ranges.year.size])
+ da_chunks.extend([(4), (season_ranges.year.size)])
+
+ da_coords = {**measure.coords}
+ da_coords.pop("time", None)
+ da_coords["year"] = season_ranges.year.values
+ da_coords["definition"] = [f"{hw_def[0]}-{hw_def[1]}-{hw_def[2]}" for hw_def in hw_definitions]
+ da_coords["percentile"] = threshold.percentile.values
+
+ template = xarray.DataArray(
+ da.random.random(da_shape, chunks=da_chunks),
+ dims=da_dims,
+ coords=da_coords
+ )
+
+ metric_data = xarray.map_blocks(
+ compute_heatwave_metrics_wrapper,
+ obj=measure,
+ args=[threshold, doy_map],
+ kwargs={
+ "hw_definitions": hw_definitions,
+ },
+ template=template
+ )
+
+ ds = xarray.Dataset(
+ dict(
+ HWF=metric_data.sel(metric=0),
+ HWN=metric_data.sel(metric=1),
+ HWD=metric_data.sel(metric=2),
+ HWA=metric_data.sel(metric=3)
+ )
+ )
+
+ start_ts = cftime.datetime(ds.year[0], 1, 1, calendar=measure.time.values[0].calendar)
+ end_ts = cftime.datetime(ds.year[-1], 1, 1, calendar=measure.time.values[0].calendar)
+ ds = ds.rename(dict(year="time")).assign_coords(dict(time=xarray.date_range(start_ts, end_ts, periods=ds.year.size, use_cftime=True)))
+
+ ds.attrs |= {
+ "description": f"Heatwave metric dataset generated by Heatwave Diagnostics Package (HDP v{get_version()})",
+ "hdp_version": get_version(),
+ "hdp_type": "metric"
+ }
+
+ ds["HWF"].attrs |= {
+ "units": "heatwave days",
+ "long_name": "Heatwave Frequency",
+ "description": "Number of days that fall within heatwave during a heatwave season"
+ }
+ ds["HWD"].attrs |= {
+ "units": "heatwave days",
+ "long_name": "Heatwave Duration",
+ "description": "Length of longest heatwave during a heatwave season"
+ }
+ ds["HWN"].attrs |= {
+ "units": "heatwave events",
+ "long_name": "Heatwave Number",
+ "description": "Number of distinct heatwaves during a heatwave season"
+ }
+ ds["HWA"].attrs |= {
+ "units": "heatwave events",
+ "long_name": "Heatwave Average",
+ "description": "Average length of heatwaves during a heatwave season"
+ }
+ ds["percentile"].attrs |= {
+ "range": "(0, 1)"
+ }
+ ds["definition"].attrs |= {
+ "first_number": "Minimum number of consecutively hot days",
+ "second_number": "Maximum number of break days after first wave",
+ "third_number": "Minimum number of consecutively hot days after the break"
+ }
+
+ for variable in ds:
+ ds[variable].attrs["history"] = combined_history
+ add_history(ds[variable], f"Heatwave metrics generated by HDP v{get_version()}")
+
+ if include_threshold:
+ ds[threshold.name] = threshold
+
+ return ds
+
+
+def compute_group_metrics(measures: xarray.Dataset, thresholds:xarray.Dataset, hw_definitions: list, include_threshold: bool=False, check_variables: bool=True) -> xarray.Dataset:
+ metric_sets = []
+ for measure_name in list(measures.keys()):
+ measure = measures[measure_name]
+ for threshold_name in list(thresholds.keys()):
+ threshold = thresholds[threshold_name]
+ if threshold.attrs["baseline_variable"] == measure.attrs["baseline_variable"]:
+ hw_metrics = compute_individual_metrics(measure, threshold, hw_definitions, include_threshold, check_variables)
+ var_renames = {name: f"{measure_name}.{threshold_name}.{name}" for name in list(hw_metrics.keys()) if name != threshold_name}
+ metric_sets.append(hw_metrics.rename(var_renames))
+
+ aggr_ds = xarray.merge(metric_sets)
+ aggr_ds.attrs["variable_naming_desc"] = "(heat measure).(threshold used).(heatwave metric)"
+ aggr_ds.attrs["variable_naming_delimeter"] = "."
+ return aggr_ds
+
+
+def compute_metrics_io(output_path: str,
+ measure_path: str,
+ measure_var: str,
+ threshold_path: str,
+ hw_definitions: list,
+ include_threshold: bool=False,
+ override_threshold_var: str=None,
+ overwrite: bool=False) -> None:
+ """
+ Computes heatwave metrics from path inputs instead of manually supplied xarray Datasets/DataArrays (automates reading from and writing to disk).
+ Resulting metrics are written directly to disk instead of holding in memory.
+
+ :param output_path: Path to write dataset(s) to, can be a zarr store (faster) or netCDF file (slower).
+ :type output_path: str
+ :param measure_path: Path to heat measure dataset formatted by the HDP.
+ :type measure_path: str
+ :param measure_var: Name of measure variable to use from specified dataset.
+ :type measure_var: str
+ :param threshold_path: Path to threshold dataset formatted by the HDP.
+ :type threshold_path: str
+ :param hw_definitions: Definitions to compute heatwave metrics over.
+ :type hw_definitions: list
+ :param include_threshold: (Optional) Whether or not to include the threshold dataset in the resulting output. Default is False.
+ :type include_threshold: bool
+ :param override_threshold_var: (Optional) Override threshold variable to use when computing metrics. If left unspecified, the format "threshold_{measure_var}" will be used.
+ :type override_threshold_var: str
+ :param overwrite: (Optional) Whether or not to overwrite an existing dataset at the output_path. Defaults to False.
+ :type overwrite: bool
+ :return: None
+ :rtype: None
+ """
+ output_path = Path(output_path)
+ measure_path = Path(measure_path)
+ threshold_path = Path(threshold_path)
+ check_variables = True
+
+ if override_threshold_var is None:
+ threshold_var = f"threshold_{measure_var}"
+ check_variables = False
+ else:
+ threshold_var = override_threshold_var
+
+ if output_path.exists() and not overwrite:
+ raise FileExistsError(f"Overwrite parameter set to False and file exists at '{output_path}'.")
+
+ if not output_path.parent.exists():
+ if overwrite:
+ makedirs(output_path)
+ else:
+ raise FileExistsError(f"Overwrite parameter set to False and directory '{output_path.parent}' does not exist.")
+
+ if output_path.suffix not in [".zarr", ".nc"]:
+ raise ValueError(f"File type '{output_path.suffix}' from '{output_path}' not supported.")
+
+ if measure_path.suffix == ".zarr" and measure_path.is_dir():
+ measure_data = xarray.open_zarr(measure_path)[measure_var]
+ else:
+ measure_data = xarray.open_dataset(measure_path)[measure_var]
+
+ # The heatwave indexing requires the full time axis in a single chunk (see compute_individual_metrics).
+ measure_data = measure_data.chunk(dict(time=-1))
+
+ if threshold_path.suffix == ".zarr" and threshold_path.is_dir():
+ threshold_data = xarray.open_zarr(threshold_path)[threshold_var]
+ else:
+ threshold_data = xarray.open_dataset(threshold_path)[threshold_var]
+
+ metric_ds = compute_individual_metrics(measure_data, threshold_data, hw_definitions, include_threshold=include_threshold, check_variables=check_variables)
+
+ if output_path.suffix == ".zarr":
+ metric_ds.to_zarr(output_path)
+ else:
+ metric_ds.to_netcdf(output_path)
\ No newline at end of file
diff --git a/hdp/tests/__init__.py b/hdp/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/hdp/tests/test_heatwave_average.py b/hdp/tests/test_heatwave_average.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ff6e9d4266421228a4092b27838ef864ff4d912
--- /dev/null
+++ b/hdp/tests/test_heatwave_average.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_average
+import numpy as np
+
+
+class TestHeatwaveAverage:
+ def test_heatwave_average_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_average_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_full, season_range), np.array([100]))
+
+ def test_heatwave_average_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case1, season_range), np.array([5.5]))
+
+ def test_heatwave_average_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.allclose(heatwave_average(hot_day_case2, season_range), np.array([3.333333]))
+
+ def test_heatwave_average_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case3, season_range), np.array([1.75]))
+
+ def test_heatwave_average_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_full, season_range), np.array([5, 10, 10, 8]))
+
+ def test_heatwave_average_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case3, season_range), np.array([6, 2.5]))
+
+ def test_heatwave_average_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_average(hot_day_case3, season_range), np.array([1.5, 2]))
diff --git a/hdp/tests/test_heatwave_duration.py b/hdp/tests/test_heatwave_duration.py
new file mode 100644
index 0000000000000000000000000000000000000000..c865b498e17faf843db8033e61907311c1da6f67
--- /dev/null
+++ b/hdp/tests/test_heatwave_duration.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_duration
+import numpy as np
+
+
+class TestHeatwaveDuration:
+ def test_heatwave_duration_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_duration_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_full, season_range), np.array([100]))
+
+ def test_heatwave_duration_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case1, season_range), np.array([7]))
+
+ def test_heatwave_duration_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case2, season_range), np.array([5]))
+
+ def test_heatwave_duration_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case3, season_range), np.array([3]))
+
+ def test_heatwave_duration_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_full, season_range), np.array([5, 10, 10, 8]))
+
+ def test_heatwave_duration_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case3, season_range), np.array([6, 4]))
+
+ def test_heatwave_duration_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_duration(hot_day_case3, season_range), np.array([2, 3]))
diff --git a/hdp/tests/test_heatwave_frequency.py b/hdp/tests/test_heatwave_frequency.py
new file mode 100644
index 0000000000000000000000000000000000000000..140cb21d5ffd809eb311d79624558484ea909b1b
--- /dev/null
+++ b/hdp/tests/test_heatwave_frequency.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_frequency
+import numpy as np
+
+
+class TestHeatwaveFrequency:
+ def test_heatwave_frequency_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_frequency_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_full, season_range), np.array([100]))
+
+ def test_heatwave_frequency_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case1, season_range), np.array([11]))
+
+ def test_heatwave_frequency_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case2, season_range), np.array([10]))
+
+ def test_heatwave_frequency_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case3, season_range), np.array([7]))
+
+ def test_heatwave_frequency_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_full, season_range), np.array([5, 10, 10, 8]))
+
+ def test_heatwave_frequency_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case3, season_range), np.array([6, 5]))
+
+ def test_heatwave_frequency_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_frequency(hot_day_case3, season_range), np.array([3, 4]))
diff --git a/hdp/tests/test_heatwave_number.py b/hdp/tests/test_heatwave_number.py
new file mode 100644
index 0000000000000000000000000000000000000000..232292ad743de7c1cb63919c2b7073dc1385981a
--- /dev/null
+++ b/hdp/tests/test_heatwave_number.py
@@ -0,0 +1,54 @@
+from hdp.metric import heatwave_number
+import numpy as np
+
+
+class TestHeatwaveNumber:
+ def test_heatwave_number_null_case(self):
+ hot_day_null = np.zeros(100, dtype=int)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_null, season_range), np.array([0]))
+
+ def test_heatwave_number_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 100]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_full, season_range), np.array([1]))
+
+ def test_heatwave_number_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case1.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case1, season_range), np.array([2]))
+
+ def test_heatwave_number_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 3],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case2.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case2, season_range), np.array([3]))
+
+ def test_heatwave_number_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case3, season_range), np.array([4]))
+
+ def test_heatwave_number_season_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ season_range = np.array([[0, 5], [0, 10], [20, 30], [42, 50]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_full, season_range), np.array([1, 1, 1, 1]))
+
+ def test_heatwave_number_season_case1(self):
+ hot_day_case3 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case3, season_range), np.array([1, 2]))
+
+ def test_heatwave_number_season_case2(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0],
+ dtype=int)
+ season_range = np.array([[0, 8], [8, hot_day_case3.size]], dtype=int)
+ assert np.array_equal(heatwave_number(hot_day_case3, season_range), np.array([2, 2]))
diff --git a/hdp/tests/test_index_heatwaves.py b/hdp/tests/test_index_heatwaves.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ee22c1b857a137e805f4cd9421a405492c0b66
--- /dev/null
+++ b/hdp/tests/test_index_heatwaves.py
@@ -0,0 +1,41 @@
+from hdp.metric import index_heatwaves
+import numpy as np
+import pytest
+
+
+class TestIndexHeatwave:
+ def test_index_heatwaves_null_case(self):
+ hot_day_null = np.zeros(100, dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_null, 1, 1, 1), np.zeros(hot_day_null.size))
+ assert np.array_equal(index_heatwaves(hot_day_null, 1, 0, 1), np.zeros(hot_day_null.size))
+ assert np.array_equal(index_heatwaves(hot_day_null, 0, 0, 1), np.zeros(hot_day_null.size))
+
+ def test_index_heatwaves_full_case(self):
+ hot_day_full = np.ones(100, dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_full, 1, 1, 1), np.ones(hot_day_full.size))
+ assert np.array_equal(index_heatwaves(hot_day_full, 1, 0, 1), np.ones(hot_day_full.size))
+ assert np.array_equal(index_heatwaves(hot_day_full, 0, 0, 1), np.ones(hot_day_full.size))
+
+ def test_index_heatwaves_case1(self):
+ hot_day_case1 = np.array(
+ [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
+ dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_case1, 1, 1, 1), [0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case1, 1, 0, 1), [0, 1, 1, 1, 1, 0, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case1, 0, 0, 1), [0, 1, 1, 1, 1, 0, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0])
+
+ def test_index_heatwaves_case2(self):
+ hot_day_case2 = np.array(
+ [0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1],
+ dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_case2, 1, 1, 1), [0, 1, 0, 1, 1, 0, 2, 2, 0, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 4])
+ assert np.array_equal(index_heatwaves(hot_day_case2, 1, 0, 1), [0, 1, 0, 2, 2, 0, 3, 3, 0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 0, 5])
+ assert np.array_equal(index_heatwaves(hot_day_case2, 0, 0, 1), [0, 1, 0, 2, 2, 0, 3, 3, 0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 0, 5])
+
+ def test_index_heatwaves_case3(self):
+ hot_day_case3 = np.array(
+ [0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
+ dtype=bool)
+ assert np.array_equal(index_heatwaves(hot_day_case3, 1, 1, 1), [0, 0, 0, 1, 1, 0, 1, 0, 2, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case3, 1, 0, 1), [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0])
+ assert np.array_equal(index_heatwaves(hot_day_case3, 0, 0, 1), [0, 0, 0, 1, 1, 0, 2, 0, 3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0])
\ No newline at end of file
diff --git a/hdp/tests/test_utils.py b/hdp/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f58d24248d7bca9a2544bd0d7ab8a228696b236c
--- /dev/null
+++ b/hdp/tests/test_utils.py
@@ -0,0 +1,57 @@
+from hdp.utils import *
+import numpy as np
+from math import isclose
+from xarray import DataArray
+
+def test_get_time_stamp():
+ assert type(get_time_stamp()) is str
+
+
+def test_get_version():
+ assert type(get_version()) is str
+
+
+def test_control_dataarray():
+ control_da = generate_test_control_dataarray(grid_shape=(1,1), start_date="2000", end_date="2100")
+ assert type(control_da) is DataArray
+ var = control_da.name
+ assert control_da.attrs["units"] == "degC"
+ assert control_da.dims == ("lon", "lat", "time")
+ assert control_da.dtype == float
+ assert control_da.time.values[0].calendar == "noleap"
+ assert control_da.time.values.size >= 365
+ assert np.sum(np.isnan(control_da)) == 0
+
+ control_slope = np.polyfit(np.arange(control_da["time"].size), control_da.mean(dim=["lat", "lon"]).values, 1)[0]
+ assert np.abs(control_slope) < 0.01
+
+
+def test_warming_dataarray():
+ warming_da = generate_test_warming_dataarray(grid_shape=(1,1), start_date="2000", end_date="2100")
+ avg_da = warming_da.mean(dim=["lat", "lon"]).values
+ warm_slope = np.polyfit(np.arange(avg_da.size), avg_da, 1)[0]
+
+ assert warm_slope > 0
+ assert not isclose(warm_slope, 0)
+
+
+def test_rh_dataarray():
+ rh_da = generate_test_rh_dataarray()
+
+ assert rh_da.max() <= 1
+ assert rh_da.min() >= 0
+
+
+def test_defaults_compatibility():
+ control_da = generate_test_control_dataarray()
+ warming_da = generate_test_warming_dataarray()
+ rh_da = generate_test_rh_dataarray()
+
+ assert control_da.shape == warming_da.shape
+ assert warming_da.shape == rh_da.shape
+
+ assert control_da.dims == warming_da.dims
+ assert warming_da.dims == rh_da.dims
+
+ assert control_da.name == warming_da.name
+ assert control_da.units == warming_da.units
\ No newline at end of file
diff --git a/hdp/tests/test_workflow.py b/hdp/tests/test_workflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..5750512fefd1f8bc7bb49c5f4c287b5c78cad30d
--- /dev/null
+++ b/hdp/tests/test_workflow.py
@@ -0,0 +1,99 @@
+from hdp.graphics.notebook import create_notebook
+import pytest
+import hdp.utils
+import hdp.measure
+import hdp.threshold
+import hdp.metric
+import numpy as np
+
+
+@pytest.fixture(scope="function")
+def temp_output_dir(tmp_path_factory):
+ return tmp_path_factory.mktemp("output_dir")
+
+
+def test_full_data_workflow(temp_output_dir):
+ grid_shape = (2, 3)
+
+ baseline_temp = hdp.utils.generate_test_control_dataarray(grid_shape=grid_shape).rename("temp")
+ baseline_rh = hdp.utils.generate_test_rh_dataarray(grid_shape=grid_shape).rename("rh")
+ baseline_measures = hdp.measure.format_standard_measures([baseline_temp], rh=baseline_rh)
+
+ percentiles = np.arange(0.9, 1, 0.01)
+
+ thresholds = hdp.threshold.compute_thresholds(baseline_measures, percentiles=percentiles)
+
+ test_temp = hdp.utils.generate_test_warming_dataarray(grid_shape=grid_shape).rename("temp")
+ test_rh = baseline_rh
+
+ hw_definitions = [[3,0,0], [3,1,1], [4,2,0], [4,1,3], [5,0,1], [5,1,4]]
+
+ test_measures = hdp.measure.format_standard_measures([test_temp], rh=test_rh)
+ metrics = hdp.metric.compute_group_metrics(test_measures, thresholds, hw_definitions)
+
+ metrics = metrics.compute()
+ thresholds = thresholds.compute()
+
+ assert (thresholds.percentile.values == percentiles).all()
+ assert len(thresholds.data_vars) == 2
+
+ assert metrics.definition.values[0] == "3-0-0"
+ assert metrics.definition.values[1] == "3-1-1"
+ assert metrics.definition.values[2] == "4-2-0"
+ assert metrics.definition.values[3] == "4-1-3"
+ assert metrics.definition.values[4] == "5-0-1"
+ assert metrics.definition.values[5] == "5-1-4"
+ assert (metrics.percentile.values == percentiles).all()
+
+ metric_means = metrics.mean()
+
+ assert metric_means["temp.temp_threshold.HWF"] >= metric_means["temp.temp_threshold.HWD"]
+ assert metric_means["temp.temp_threshold.HWD"] >= metric_means["temp.temp_threshold.HWA"]
+
+ for var in metrics:
+ assert metrics[var].shape == (metrics.percentile.size, metrics.definition.size, metrics.lon.size, metrics.lat.size, metrics.time.size)
+ assert metrics[var].dtype == int
+ if "HWF" in var or "HWD" in var:
+ assert metrics[var].attrs["units"] == 'heatwave days', f"Variable '{var}' has incorrect units '{metrics[var].attrs["units"]}'"
+ elif "HWN" in var or "HWA" in var:
+ assert metrics[var].attrs["units"] == 'heatwave events', f"Variable '{var}' has incorrect units '{metrics[var].attrs["units"]}'"
+ else:
+ assert False, f"Cannot determine primary heatwave metric from variable '{var}'."
+
+ figure_notebook = create_notebook(metrics)
+ figure_notebook.save_notebook(f"{temp_output_dir}/sample_hw_summary_figures.ipynb")
+
+
+def test_include_threshold(temp_output_dir):
+ grid_shape = (2, 3)
+
+ baseline_temp = hdp.utils.generate_test_control_dataarray(grid_shape=grid_shape).rename("temp")
+ test_temp = hdp.utils.generate_test_warming_dataarray(grid_shape=grid_shape).rename("temp")
+
+ baseline_measures = hdp.measure.format_standard_measures([baseline_temp])
+ test_measures = hdp.measure.format_standard_measures([test_temp])
+
+ percentiles = np.arange(0.9, 1, 0.02)
+ thresholds = hdp.threshold.compute_thresholds(baseline_measures, percentiles=percentiles)
+
+ hw_definitions = [[3, 0, 0], [3, 1, 1]]
+
+ metrics_with = hdp.metric.compute_group_metrics(test_measures, thresholds, hw_definitions, include_threshold=True).compute()
+ metrics_without = hdp.metric.compute_group_metrics(test_measures, thresholds, hw_definitions, include_threshold=False).compute()
+ thresholds = thresholds.compute()
+
+ # The threshold variable is embedded under its own name only when include_threshold=True.
+ assert "temp_threshold" in metrics_with.data_vars
+ assert "temp_threshold" not in metrics_without.data_vars
+
+ # The metric variables are unaffected by include_threshold.
+ metric_vars = [var for var in metrics_with.data_vars if var != "temp_threshold"]
+ assert set(metric_vars) == set(metrics_without.data_vars)
+
+ # The embedded threshold matches the source threshold exactly.
+ embedded = metrics_with["temp_threshold"]
+ source = thresholds["temp_threshold"]
+ assert embedded.broadcast_like(source).equals(source.broadcast_like(embedded))
+
+ figure_notebook = create_notebook(metrics_with)
+ figure_notebook.save_notebook(f"{temp_output_dir}/sample_hw_summary_figures.ipynb")
diff --git a/hdp/threshold.py b/hdp/threshold.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b33118b8f685012fc676c0736a04580857888c0
--- /dev/null
+++ b/hdp/threshold.py
@@ -0,0 +1,289 @@
+#!/usr/bin/env python
+import xarray
+import numpy as np
+import numba as nb
+from os.path import isdir
+from os import makedirs
+from pathlib import Path
+from hdp.utils import add_history, get_version
+import dask.array as da
+
+
+def datetimes_to_windows(datetimes: np.ndarray, window_radius: int) -> np.ndarray:
+ """
+ Generate rolling window sample of the day of year for each time index in the specified time series. Example below:
+
+ Day of year values for datetimes: 1 2 3 4 5 6
+ Window radius: 1
+ Result: [6 1 2], [1 2 3], [2 3 4], [3 4 5], [4 5 6], [5 6 1]
+
+
+ :param datetimes: Array of datetime objects corresponding to the dataset's time dimension
+ :type datetimes: np.ndarray
+ :param window_radius: Radius of each window
+ :type window_radius: int
+ :return: Two dimensional array where each index of the first dimension corresponds to the time dimension and the second dimension stores the indices of each window.
+ :rtype: np.ndarray
+ """
+ day_of_yr_to_index = {}
+ for index, date in enumerate(datetimes):
+ if date.dayofyr in day_of_yr_to_index.keys():
+ day_of_yr_to_index[date.dayofyr].append(index)
+ else:
+ day_of_yr_to_index[date.dayofyr] = [index]
+
+ time_index = np.zeros((len(day_of_yr_to_index), np.max([len(x) for x in day_of_yr_to_index.values()])), int) - 1
+
+ for index, day_of_yr in enumerate(day_of_yr_to_index):
+ for i in range(len(day_of_yr_to_index[day_of_yr])):
+ time_index[index, i] = day_of_yr_to_index[day_of_yr][i]
+
+ window_samples = np.zeros((len(day_of_yr_to_index), 2*window_radius+1, time_index.shape[1]), int)
+
+ for day_of_yr in range(window_samples.shape[0]):
+ for window_index in range(window_samples.shape[1]):
+ sample_index = day_of_yr + window_radius - window_index
+ if sample_index >= time_index.shape[0]:
+ sample_index = time_index.shape[0] - sample_index
+ window_samples[day_of_yr, window_index] = time_index[sample_index]
+ return window_samples.reshape((window_samples.shape[0], window_samples.shape[1]*window_samples.shape[2]))
+
+
+@nb.guvectorize(
+ [(nb.float32[:],
+ nb.int64[:, :],
+ nb.float64[:],
+ nb.float64[:, :])],
+ '(t), (d, b), (p) -> (d, p)'
+)
+def compute_percentiles(temperatures: np.ndarray, window_samples: np.ndarray, percentiles: np.ndarray, output: np.ndarray):
+ """
+ Generalized universal function that computes the temperatures for multiple percentiles using time index window samples.
+
+ :param temperatures: Dataset containing temperatures to compute percentiles from
+ :type temperatures: np.ndarray
+ :param window_samples: Array containing "windows" of indices cenetered at each day of the year
+ :type window_samples: np.ndarray
+ :param percentiles: Array of perecentiles to compute [0, 1]
+ :type percentiles: np.ndarray
+ :param output: Array to write percentiles to
+ :type output: np.ndarray
+ :return: None
+ :rtype: None
+ """
+ for doy_index in range(window_samples.shape[0]):
+ doy_temps = np.zeros(window_samples[doy_index].size)
+ for index, temperature_index in enumerate(window_samples[doy_index]):
+ doy_temps[index] = temperatures[temperature_index]
+ output[doy_index] = np.quantile(doy_temps, percentiles)
+
+
+def compute_percentiles_wrapper(baseline_data, rolling_windows, percentiles):
+ threshold_da = xarray.apply_ufunc(compute_percentiles,
+ baseline_data,
+ rolling_windows,
+ percentiles,
+ dask="parallelized",
+ input_core_dims=[["time"], ["doy", "t_index"], ["percentile"]],
+ output_core_dims=[["doy", "percentile"]],
+ keep_attrs="override",
+ dask_gufunc_kwargs={
+ 'allow_rechunk': False
+ })
+ return threshold_da
+
+
+def compute_threshold(baseline_data: xarray.DataArray, percentiles: np.ndarray, no_season: bool=False, rolling_window_size: int=7, fixed_value: float=None) -> xarray.Dataset:
+ """
+ Computes percentile and, optionally, fixed value thresholds for a baseline measurements.
+
+
+ :param baseline_data: DataArrays with baseline measurements to calculate thresholds from.
+ :type baseline_data: xarray.DataArray
+ :param percentiles: List of percentiles to calculate for each baseline.
+ :type percentiles: np.ndarray
+ :param no_season: (Optional) Instead of taking window samples at each day of year to get a seasonally-varying threshold, calculate a single percentile for the entire year. Defaults to False.
+ :type no_season: bool
+ :param rolling_window_size: (Optional) Size of rolling windows to use when calculating the percentiles. Defaults to 7.
+ :type rolling_window_size: int
+ :param fixed_value: (Optional) Value to use for fixed threshold (non-seasonally varying). Defaults to None.
+ :type fixed_value: float
+ :return: Aggregated dataset of all thresholds generated.
+ :rtype: xarray.Dataset
+ """
+ if "member" in baseline_data.dims:
+ member_datasets = []
+ for member in baseline_data.member.values:
+ member_slice = baseline_data.sel(member=member).drop_vars("member")
+ member_datasets.append(member_slice)
+ baseline_data = xarray.concat(member_datasets, dim="time")
+
+ baseline_data = baseline_data.chunk(dict(time=-1)).astype(np.float32)
+
+ percentiles = np.array(percentiles)
+
+ rolling_windows_indices = datetimes_to_windows(baseline_data.time.values, rolling_window_size)
+ rolling_windows_coords = {
+ "doy": np.arange(rolling_windows_indices.shape[0]),
+ "t_index": np.arange(rolling_windows_indices.shape[1])
+ }
+ rolling_windows = xarray.DataArray(data=rolling_windows_indices,
+ coords=rolling_windows_coords)
+
+ percentiles = xarray.DataArray(data=percentiles,
+ coords={"percentile": percentiles})
+
+ da_dims = []
+ da_shape = []
+ da_chunks = []
+
+ for index, dim in enumerate(baseline_data.dims):
+ if dim != "time":
+ da_dims.append(dim)
+ da_shape.append(baseline_data.shape[index])
+ da_chunks.append(baseline_data.chunks[index])
+
+ da_dims.extend(["doy", "percentile"])
+ da_shape.extend([rolling_windows_indices.shape[0], percentiles.values.size])
+ da_chunks.extend([(rolling_windows_indices.shape[0]), (percentiles.values.size)])
+
+
+ da_coords = {coord: baseline_data.coords[coord] for coord in baseline_data.coords if coord != "time"}
+ da_coords["doy"] = np.arange(rolling_windows_indices.shape[0])
+ da_coords["percentile"] = percentiles.values
+
+ template = xarray.DataArray(
+ da.random.random(da_shape, chunks=da_chunks),
+ dims=da_dims,
+ coords=da_coords
+ )
+
+ threshold_da = xarray.map_blocks(
+ compute_percentiles_wrapper,
+ obj=baseline_data,
+ kwargs={
+ "rolling_windows": rolling_windows,
+ "percentiles": percentiles
+ },
+ template=template
+ )
+
+ add_history(threshold_da, f"Threshold data computed by HDP v{get_version()}.\n")
+ if "long_name" in threshold_da.attrs:
+ add_history(threshold_da, f"Metadata updated: 'long_name' value '{threshold_da.attrs["long_name"]}' overwritten by HDP.\n")
+
+ threshold_da.attrs |= {
+ "long_name": f"Percentile threshold values for baseline variable '{baseline_data.name}'",
+ "baseline_variable": baseline_data.name,
+ "baseline_start_time": f"{str(baseline_data.time.values[0])}",
+ "baseline_end_time": f"{str(baseline_data.time.values[-1])}",
+ "baseline_calendar": f"{str(baseline_data.time.values[-1].calendar)}",
+ "param_percentiles": str(percentiles.values),
+ "param_noseason": str(no_season),
+ "param_rolling_window_size": str(rolling_window_size),
+ "param_fixed_value": str(fixed_value),
+ "hdp_type": "threshold"
+ }
+
+ ds = xarray.Dataset(
+ data_vars={
+ f"{baseline_data.name}_threshold": threshold_da,
+ },
+ coords=dict(
+ lon=(["lon"], threshold_da.lon.values),
+ lat=(["lat"], threshold_da.lat.values),
+ doy=np.arange(0, rolling_windows.shape[0]),
+ percentile=percentiles
+ ),
+ attrs=dict(
+ description=f"Extreme heat threshold dataset generated by Heatwave Diagnostics Package (HDP v{get_version()})",
+ hdp_version=get_version(),
+ )
+ )
+ ds["doy"].attrs = dict(units="day_of_year", baseline_calendar=str(baseline_data.time.values[0].calendar))
+ return ds
+
+
+def compute_thresholds(baseline_dataset: list[xarray.DataArray], percentiles: np.ndarray, no_season: bool=False, rolling_window_size: int=7, fixed_value: float=None) -> xarray.Dataset:
+ """
+ Wrapper function for generating multiple thresholds with hdp.threshold.compute_threshold.
+ Computes percentile and, optionally, fixed value thresholds for a list of baseline measurements.
+
+
+ :param baseline_dataset: Dataset containing baseline measurements to calculate thresholds from, where each data variable is used to compute a threshold.
+ :type baseline_dataset: xarray.Dataset
+ :param percentiles: List of percentiles to calculate for each baseline.
+ :type percentiles: np.ndarray
+ :param no_season: (Optional) Instead of taking window samples at each day of year to get a seasonally-varying threshold, calculate a single percentile for the entire year. Defaults to False.
+ :type no_season: bool
+ :param rolling_window_size: Size of rolling windows to use when calculating the percentiles.
+ :type rolling_window_size: int
+ :param fixed_value: Value to use for fixed threshold (non-seasonally varying).
+ :type fixed_value: float
+ :return: Aggregated dataset of all thresholds generated.
+ :rtype: xarray.Dataset
+ """
+ threshold_datasets = []
+ for var_name in baseline_dataset:
+ threshold_datasets.append(compute_threshold(baseline_dataset[var_name], percentiles, no_season, rolling_window_size, fixed_value))
+ return xarray.merge(threshold_datasets)
+
+
+def compute_threshold_io(baseline_path: str,
+ baseline_var: str,
+ output_path: str,
+ percentiles: np.ndarray,
+ no_season: bool=False,
+ rolling_window_size: int=7,
+ fixed_value: float=None,
+ overwrite: bool=False) -> None:
+ """
+ Computes thresholds from path inputs instead of manually supplied xarray Datasets/DataArrays (automates reading from and writing to disk).
+ Resulting threshold datasets are written directly to disk instead of holding in memory.
+
+ :param baseline_path: Path to netCDF or zarr store containing baseline measurements to compute thresholds from.
+ :type baseline_path: str
+ :param baseline_var: Variable read from the dataset at the specified path.
+ :type baseline_var: str
+ :param output_path: Path to write dataset(s) to, can be a zarr store (faster) or netCDF file (slower).
+ :type output_path: str
+ :param percentiles: List of percentiles to calculate for each baseline.
+ :type percentiles: np.ndarray
+ :param no_season: (Optional) Instead of taking window samples at each day of year to get a seasonally-varying threshold, calculate a single percentile for the entire year. Defaults to False.
+ :type no_season: bool
+ :param rolling_window_size: (Optional) Size of rolling windows to use when calculating the percentiles. Defaults to 7.
+ :type rolling_window_size: int
+ :param fixed_value: (Optional) Value to use for fixed threshold (non-seasonally varying). Defaults to None.
+ :type fixed_value: float
+ :param overwrite: (Optional) Whether or not to overwrite existing datasets at the output_path. Defaults to False
+ :type overwrite: bool
+ :return: None
+ :rtype: None
+ """
+ output_path = Path(output_path)
+ baseline_path = Path(baseline_path)
+
+ if output_path.exists() and not overwrite:
+ raise FileExistsError(f"Overwrite parameter set to False and file exists at '{output_path}'.")
+
+ if not output_path.parent.exists():
+ if overwrite:
+ makedirs(output_path)
+ else:
+ raise FileExistsError(f"Overwrite parameter set to False and directory '{output_path.parent}' does not exist.")
+
+ if output_path.suffix not in [".zarr", ".nc"]:
+ raise ValueError(f"File type '{output_path.suffix}' from '{output_path}' not supported.")
+
+ if baseline_path.suffix == ".zarr" and baseline_path.is_dir():
+ baseline_data = xarray.open_zarr(baseline_path)[baseline_var]
+ else:
+ baseline_data = xarray.open_dataset(baseline_path)[baseline_var]
+
+ baseline_data.attrs["baseline_source"] = str(baseline_path)
+ threshold_ds = compute_threshold(baseline_data, percentiles, no_season, rolling_window_size, fixed_value)
+
+ if output_path.suffix == ".zarr":
+ threshold_ds.to_zarr(output_path)
+ else:
+ threshold_ds.to_netcdf(output_path)
\ No newline at end of file
diff --git a/hdp/utils.py b/hdp/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a71b6d657d45764b2621b9be0e3539dbfb96ac30
--- /dev/null
+++ b/hdp/utils.py
@@ -0,0 +1,145 @@
+from time import time
+from importlib.metadata import version
+import numpy as np
+import dask.array as da
+import xarray
+import datetime
+import cftime
+
+
+def get_time_stamp():
+ return datetime.datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H:%M')
+
+
+def add_history(ds, msg):
+ if "history" in ds.attrs:
+ ds.attrs["history"] += f"({get_time_stamp()}) {msg}\n"
+ else:
+ ds.attrs["history"] = f"({get_time_stamp()}) History metadata initialized by HDP v{get_version()}.\n"
+ ds.attrs["history"] += f"({get_time_stamp()}) {msg}\n"
+ return ds
+
+
+def get_version():
+ return version('hdp_python')
+
+
+def get_func_description(func):
+ lines = func.__doc__.split("\n")
+ desc = ""
+ for line in lines:
+ if ":param" in line:
+ break
+ line = line.strip()
+ if line != "":
+ desc += line.strip() + " "
+ return desc
+
+
+def generate_test_warming_dataarray(start_date="2000-01-01", end_date="2049-12-31", grid_shape=(2, 3), warming_period=100, add_noise=False):
+ """
+ Generates a synthetic warming temperature DataArray for testing.
+
+ Wraps :func:`generate_test_control_dataarray` and adds a linear warming trend
+ over the specified warming period (in years).
+
+ :param start_date: Start date of the time series in YYYY-MM-DD format. Defaults to "2000-01-01".
+ :type start_date: str
+ :param end_date: End date of the time series in YYYY-MM-DD format. Defaults to "2049-12-31".
+ :type end_date: str
+ :param grid_shape: Tuple of (lat, lon) grid dimensions. Defaults to (2, 3).
+ :type grid_shape: tuple
+ :param warming_period: Number of years over which 1 degree of warming is applied. Defaults to 100.
+ :type warming_period: int
+ :param add_noise: If True, adds random noise to create variance. Defaults to False.
+ :type add_noise: bool
+ :return: Synthetic warming temperature DataArray in degrees Celsius.
+ :rtype: xarray.DataArray
+ """
+ base_data = generate_test_control_dataarray(start_date=start_date, end_date=end_date, grid_shape=grid_shape, add_noise=add_noise)
+ base_data += xarray.DataArray(np.arange(base_data["time"].size) / (365*warming_period), dims=["time"], coords={"time": base_data["time"]})
+ return base_data
+
+
+def generate_test_rh_dataarray(start_date="2000-01-01", end_date="2049-12-31", grid_shape=(2, 3)):
+ """
+ Generates a synthetic relative humidity DataArray for testing.
+
+ Derived from :func:`generate_test_control_dataarray` and scaled to a relative
+ humidity range with units of g/g.
+
+ :param start_date: Start date of the time series in YYYY-MM-DD format. Defaults to "2000-01-01".
+ :type start_date: str
+ :param end_date: End date of the time series in YYYY-MM-DD format. Defaults to "2049-12-31".
+ :type end_date: str
+ :param grid_shape: Tuple of (lat, lon) grid dimensions. Defaults to (2, 3).
+ :type grid_shape: tuple
+ :return: Synthetic relative humidity DataArray with units "g/g".
+ :rtype: xarray.DataArray
+ """
+ base_data = generate_test_control_dataarray(start_date=start_date, end_date=end_date, grid_shape=grid_shape)
+ base_data = abs(base_data / base_data.max() - 0.3)
+ base_data = base_data.rename("test_rh_data")
+ base_data.attrs["units"] = 'g/g'
+ return base_data
+
+
+def generate_test_control_dataarray(start_date="1700-01-01", end_date="1749-12-31", grid_shape=(2, 3), add_noise=False, seed=0):
+ """
+ Generates a synthetic control temperature DataArray with a seasonal cycle for testing.
+
+ Produces a no-leap-calendar daily time series with a sinusoidal temperature pattern
+ and an optional latitudinal gradient. Used as the baseline (control) input in unit tests.
+
+ :param start_date: Start date of the time series in YYYY-MM-DD format. Defaults to "1700-01-01".
+ :type start_date: str
+ :param end_date: End date of the time series in YYYY-MM-DD format. Defaults to "1749-12-31".
+ :type end_date: str
+ :param grid_shape: Tuple of (lat, lon) grid dimensions. Defaults to (2, 3).
+ :type grid_shape: tuple
+ :param add_noise: If True, adds random noise to create variance across definitions and percentiles. Defaults to False.
+ :type add_noise: bool
+ :param seed: Random seed for reproducibility when add_noise is True. Defaults to 0.
+ :type seed: int
+ :return: Synthetic control temperature DataArray in degrees Celsius.
+ :rtype: xarray.DataArray
+ """
+ time_values = xarray.date_range(
+ start=start_date,
+ end=end_date,
+ freq="D",
+ calendar="noleap",
+ use_cftime=True
+ )
+ north_seasonal_ts = 20+2*np.sin(2*np.pi*((270 + np.arange(time_values.size, dtype=float)) / 365))
+ north_seasonal_vals = np.broadcast_to(north_seasonal_ts, (grid_shape[0], grid_shape[1], north_seasonal_ts.size))
+
+ south_seasonal_ts = 20+2*np.sin(2*np.pi*((90 + np.arange(time_values.size, dtype=float)) / 365))
+ south_seasonal_vals = np.broadcast_to(south_seasonal_ts, (grid_shape[0], grid_shape[1], south_seasonal_ts.size))
+
+ temperature_seasonal_vals = np.zeros((grid_shape[0], grid_shape[1], north_seasonal_ts.size))
+ temperature_seasonal_vals[:, grid_shape[1]//2:, :] = north_seasonal_vals[:, grid_shape[1]//2:, :]
+ temperature_seasonal_vals[:, :grid_shape[1]//2, :] = south_seasonal_vals[:, :grid_shape[1]//2, :]
+
+ if add_noise:
+ np.random.seed(seed)
+ temperature_seasonal_vals += np.random.random(temperature_seasonal_vals.shape)*(np.std(temperature_seasonal_vals) / 2)
+
+ lat_vals = np.linspace(-90, 90, grid_shape[1], dtype=float)
+
+ lat_grad = np.broadcast_to(np.abs(lat_vals) / 90, grid_shape)
+ temperature_seasonal_vals = temperature_seasonal_vals - 10*np.broadcast_to(lat_grad[:, :, None], temperature_seasonal_vals.shape)
+
+ return xarray.DataArray(
+ data=temperature_seasonal_vals,
+ dims=["lon", "lat", "time"],
+ coords={
+ "lon": np.linspace(-180, 180, grid_shape[0], dtype=float),
+ "lat": lat_vals,
+ "time": time_values
+ },
+ name="test_temperature_data",
+ attrs={
+ "units": "degC"
+ }
+ ).chunk(dict(time=-1, lat=2, lon=2))
\ No newline at end of file
|