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 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
|
from numpy import argsort as numpy_argsort
from numpy import dtype as numpy_dtype
from numpy import sort as numpy_sort
from operator import attrgetter, itemgetter
from itertools import izip
#from .ancillaryvariables import AncillaryVariables
#from .comparison import gt
from .coordinate import AuxiliaryCoordinate
from .coordinatereference import CoordinateReference
from .field import Field, FieldList
#from .fieldlist import FieldList
from .query import gt
from .units import Units
from .functions import (flat, RTOL, ATOL, equals, hash_array, allclose)
from .functions import inspect as cf_inspect
from .data.data import Data
from .data.filearray import FileArray
_dtype_float = numpy_dtype(float)
## --------------------------------------------------------------------
## Global properties, as defined in Appendix A of the CF conventions.
## --------------------------------------------------------------------
#_global_properties = set(('comment',
# 'Conventions',
# 'history',
# 'institution',
# 'references',
# 'source',
# 'title',
# ))
# --------------------------------------------------------------------
# Data variable properties, as defined in Appendix A of the CF
# conventions, without those which are not simple. And less
# 'long_name'.
# --------------------------------------------------------------------
_signature_properties = set(('add_offset',
'calendar',
'cell_methods',
'_FillValue',
'flag_masks',
'flag_meanings',
'flag_values',
'missing_value',
'scale_factor',
'standard_error_multiplier',
'standard_name',
'units',
'valid_max',
'valid_min',
'valid_range',
))
#_standard_properties = _data_properties.union(_global_properties)
_no_units = Units()
class _HFLCache(object):
'''
A cache for coordinate and cell measure hashes, first and last values
and first and last cell bounds
'''
def __init__(self):
self.hash = {}
self.fl = {}
self.flb = {}
#--- End: def
def inspect(self):
'''
Inspect the object for debugging.
.. seealso:: `cf.inspect`
:Returns:
None
:Examples:
>>> f.inspect()
'''
print cf_inspect(self)
#--- End: def
#--- End: class
class _Meta(object):
'''
A summary of a field.
This object contains everything you need to know in order to aggregate
the field.
'''
#
_canonical_units = {}
#
_canonical_cell_methods = []
def __init__(self, f,
rtol=None, atol=None,
info=0,
relaxed_units=False,
allow_no_identity=False,
respect_valid=False,
equal_all=False,
exist_all=False,
equal=None,
exist=None,
ignore=None,
dimension=(),
relaxed_identities=False,
ncvar_identities=False):
'''
**initialization**
:Parameters:
f : cf.Field
info : int, optional
See the `aggregate` function for details.
relaxed_units : bool, optional
See the `aggregate` function for details.
allow_no_identity : bool, optional
See the `aggregate` function for details.
rtol : float, optional
See the `aggregate` function for details.
atol : float, optional
See the `aggregate` function for details.
dimension : (sequence of) str, optional
See the `aggregate` function for details.
:Examples:
'''
self._nonzero = False
self.info = info
self.sort_indices = {}
self.sort_keys = {}
self.cell_values = False
self.message = ''
strict_identities = not (relaxed_identities or ncvar_identities)
self.strict_identities = strict_identities
self.ncvar_identities = ncvar_identities
# Initialize the flag which indicates whether or not this
# field has already been aggregated
self.aggregated_field = False
# ------------------------------------------------------------
# Field
# ------------------------------------------------------------
self.field = f
self._hasData = f._hasData
self.identity = f.name(identity=strict_identities,
ncvar=ncvar_identities)
# ------------------------------------------------------------
#
# ------------------------------------------------------------
signature_override = getattr(f, 'aggregate', None)
if signature_override is not None:
self.signature = signature_override
self._nonzero = True
return
if self.identity is None:
if not allow_no_identity and self._hasData:
if info:
self.message = \
"no identity; consider setting relaxed_identities"
return
elif not self._hasData:
if info:
self.message = \
"no data array"
return
#--- End: if
domain = f.domain
items = domain.items
# ------------------------------------------------------------
# Promote selected properties to 1-d, size 1 auxiliary
# coordinates
# ------------------------------------------------------------
for property in dimension:
value = f.getprop(property, None)
if value is None:
continue
aux_coord = AuxiliaryCoordinate(properties={'long_name': property},
attributes={'id': property},
data=Data([value], units=''),
copy=False)
axis = domain.insert_axis(1)
# axis = domain.new_axis_identifier()
# print aux_coord, aux_coord.ndim, axis
domain.insert_aux(aux_coord, axes=[axis], copy=False)
f.delprop(property) ### dch COPY issue?
#--- End: for
self.units = self.canonical_units(f, self.identity,
relaxed_units=relaxed_units)
self.cell_methods = self.canonical_cell_methods(rtol=rtol, atol=atol)
# ------------------------------------------------------------
# Formula_terms
# ------------------------------------------------------------
coordrefs = items(role='r')
if not coordrefs:
self.coordrefs = ()
self.coordref_signatures = ()
else:
self.coordrefs = coordrefs.values()
self.coordref_signatures = sorted([cr.structural_signature()
for cr in self.coordrefs])
for s in self.coordref_signatures:
if s[0] is None:
if info:
self.messsage = \
"%r field can't be aggregated due to it having an unidentifiable coordinate reference" % \
f.name('')
return
#--- End: if
#--- End: if
# ------------------------------------------------------------
# Ancillary variables
# ------------------------------------------------------------
if not self.set_ancillary_variables():
return
# ------------------------------------------------------------
# Coordinate and cell measure arrays
# ------------------------------------------------------------
self.hash_values = {}
self.first_values = {}
self.last_values = {}
self.first_bounds = {}
self.last_bounds = {}
# Map axis canonical identities to their domain identifiers
#
# For example: {'time': 'dim2'}
self.id_to_axis = {}
# Map domain axis identifiers to their canonical identities
#
# For example: {'dim2': 'time'}
self.axis_to_id = {}
# Dictionaries mapping domain auxiliary coordinate identifiers
# to their auxiliary coordiante objects
aux_1d = items(role='a', ndim=1)
# A set containing the identity of each domain coordinate
#
# For example: set(['time', 'height', 'latitude',
# 'longitude'])
self.all_coord_identities = set()
self.axis = {}
for axis in domain._axes_sizes:
# List some information about each 1-d coordinate which
# spans this axis. The order of elements is arbitrary, as
# ultimately it will get sorted by each element's 'name'
# key values.
#
# For example: [{'name': 'time', 'key': 'dim0', 'units':
# <CF Units: ...>}, {'name': 'forecast_ref_time', 'key':
# 'aux0', 'units': <CF Units: ...>}]
info_dim = []
dim_coord = domain.item(axis)
if dim_coord is not None:
# ----------------------------------------------------
# 1-d dimension coordinate
# ----------------------------------------------------
identity = self.coord_has_identity_and_data(dim_coord)
if identity is None:
return
# Find the canonical units for this dimension
# coordinate
units = self.canonical_units(dim_coord, identity,
relaxed_units=relaxed_units)
info_dim.append(
{'identity' : identity,
'key' : axis,
'units' : units,
'hasbounds': dim_coord._hasbounds,
'coordrefs': self.find_coordrefs(axis, dim_coord)})
#--- End: if
# Find the 1-d auxiliary coordinates which span this axis
aux_coords = {}
for aux in aux_1d.keys():
if axis in domain.item_axes(aux): #dimensions[aux]:
aux_coords[aux] = aux_1d.pop(aux)
#--- End: for
info_aux = []
for aux, aux_coord in aux_coords.iteritems():
# ----------------------------------------------------
# 1-d auxiliary coordinate
# ----------------------------------------------------
identity = self.coord_has_identity_and_data(aux_coord)
if identity is None:
return
# Find the canonical units for this 1-d auxiliary
# coordinate
units = self.canonical_units(aux_coord, identity,
relaxed_units=relaxed_units)
info_aux.append(
{'identity' : identity,
'key' : aux,
'units' : units,
'hasbounds': aux_coord._hasbounds,
'coordrefs': self.find_coordrefs(aux, aux_coord)})
#--- End: for
# Sort the 1-d auxiliary coordinate information
info_aux.sort(key=itemgetter('identity'))
# Prepend the dimension coordinate information to the
# auxiliary coordinate information
info_1d_coord = info_dim + info_aux
if not info_1d_coord:
if info:
self.message ="\
axis has no one dimensional or scalar coordinates"
#"% field can't be aggregated due to an axis having no 1-d coordinates" %
#f.name(''))
return
#--- End: if
# Find the canonical identity for this axis
identity = info_1d_coord[0]['identity']
self.axis[identity] = \
{'ids' : tuple([i['identity'] for i in info_1d_coord]),
'keys' : tuple([i['key'] for i in info_1d_coord]),
'units' : tuple([i['units'] for i in info_1d_coord]),
'hasbounds': tuple([i['hasbounds'] for i in info_1d_coord]),
'coordrefs': tuple([i['coordrefs'] for i in info_1d_coord])}
if info_dim:
self.axis[identity]['dim_coord_index'] = 0
else:
self.axis[identity]['dim_coord_index'] = None
self.id_to_axis[identity] = axis
self.axis_to_id[axis] = identity
#--- End: for
# Create a sorted list of the axes' canonical identities
#
# For example: ['latitude', 'longitude', 'time']
self.axis_ids = sorted(self.axis)
# ------------------------------------------------------------
# N-d auxiliary coordinates
# ------------------------------------------------------------
self.nd_aux = {}
for aux, nd_aux_coord in items(role='a', ndim=gt(1)).iteritems():
# Find this N-d auxiliary coordinate's identity
identity = self.coord_has_identity_and_data(nd_aux_coord)
if identity is None:
return
# Find the canonical units
units = self.canonical_units(nd_aux_coord, identity,
relaxed_units=relaxed_units)
# Find axes' canonical identities
axes = [self.axis_to_id[axis] for axis in domain.item_axes(aux)]
axes = tuple(sorted(axes))
self.nd_aux[identity] = {
'key' : aux,
'units' : units,
'axes' : axes,
'hasbounds': nd_aux_coord._hasbounds,
'coordrefs': self.find_coordrefs(aux, nd_aux_coord)}
#--- End: for
# ------------------------------------------------------------
# Cell measures
# ------------------------------------------------------------
self.msr = {}
info_msr = {}
for key, msr in items(role='m').iteritems():
if not self.cell_measure_has_data_and_units(msr):
return
# Find the canonical units for this cell measure
units = self.canonical_units(msr,
msr.name(identity=strict_identities,
ncvar=ncvar_identities),
relaxed_units=relaxed_units)
# Find axes' canonical identities
axes = [self.axis_to_id[axis] for axis in domain.item_axes(key)]
axes = tuple(sorted(axes))
if units in info_msr:
# Check for ambiguous cell measures, i.e. those which
# have the same units and span the same axes.
for value in info_msr[units]:
if axes == value['axes']:
if info:
self.message = \
"duplicate %r cell measures" % msr.name('')
return
else:
info_msr[units] = []
#--- End: if
info_msr[units].append({'key' : key,
'axes': axes})
#--- End: for
# For each cell measure's canonical units, sort the
# information by axis identities.
for units, value in info_msr.iteritems():
value.sort(key=itemgetter('axes'))
self.msr[units] = {'keys': tuple([v['key'] for v in value]),
'axes': tuple([v['axes'] for v in value])}
#--- End: for
# ------------------------------------------------------------
# Properties and attributes
# ------------------------------------------------------------
if not (equal or exist or equal_all or exist_all):
self.properties = ()
else:
properties = f.properties
for p in ignore:
properties.pop(p, None)
if equal:
eq = dict([(p, properties[p]) for p in equal
if p in properties])
else:
eq = {}
if exist:
ex = [p for p in exist if p in properties]
else:
ex = []
eq_all = {}
ex_all = []
if equal_all or exist_all:
if equal_all:
if not equal and not exist:
eq_all = properties
elif equal and exist:
eq_all = dict([(p, properties[p]) for p in properties
if p not in ex and p not in eq])
elif equal:
eq_all = dict([(p, properties[p]) for p in properties
if p not in eq])
elif exist:
eq_all = dict([(p, properties[p]) for p in properties
if p not in ex])
elif exist_all:
if not equal and not exist:
ex_all = list(properties)
elif equal and exist:
ex_all = [p for p in properties
if p not in ex and p not in eq]
elif equal:
ex_all = [p for p in properties if p not in eq]
elif exist:
ex_all = [p for p in properties if p not in ex]
#--- End: if
self.properties = tuple(sorted(ex_all + ex +
eq_all.items() + eq.items()))
#--- End: if
# Attributes
self.attributes = set(('file',))
# ----------------------------------------------------------------
# Still here? Then create the structural signature.
# ----------------------------------------------------------------
self.respect_valid = respect_valid
self.structural_signature()
# Initialize the flag which indicates whether or not this
# field has already been aggregated
self.aggregated_field = False
self.sort_indices = {}
self.sort_keys = {}
# Finally, set the object to True
self._nonzero = True
#--- End: def
def __nonzero__(self):
'''
x.__nonzero__() <==> bool(x)
'''
return self._nonzero
#--- End: if
def __repr__(self):
'''
x.__repr__() <==> repr(x)
'''
return '<CF %s: %r>' % (self.__class__.__name__,
getattr(self, 'field', None))
#--- End: def
def __str__(self):
'''
x.__str__() <==> str(x)
'''
strings = []
for attr in sorted(self.__dict__):
strings.append('%s.%s = %r' % (self.__class__.__name__, attr,
getattr(self, attr)))
return '\n'.join(strings)
#--- End: def
def coordinate_values(self):
'''
'''
string = ['First cell: '+str(self.first_values)]
string.append('Last cell: '+str(self.last_values))
string.append('First bounds: ' +str(self.first_bounds))
string.append('Last bounds: ' +str(self.last_bounds))
return '\n'.join(string)
#--- End: def
def copy(self):
'''
'''
new = _Meta.__new__(_Meta)
new.__dict__ = self.__dict__.copy()
new.field = new.field.copy()
return new
def canonical_units(self, variable, identity, relaxed_units=False):
'''
Updates the `_canonical_units` attribute.
:Parameters:
variable : cf.Variable
identity : str
relaxed_units : bool
See the `cf.aggregate` for details.
:Returns:
out : cf.Units or None
:Examples:
'''
var_units = variable.Units
_canonical_units = self._canonical_units
if identity in _canonical_units:
if var_units:
for u in _canonical_units[identity]:
if var_units.equivalent(u):
return u
#--- End: for
# Still here?
_canonical_units[identity].append(var_units)
elif relaxed_units or variable.dtype.kind == 'S':
var_units = _no_units
else:
if var_units:
_canonical_units[identity] = [var_units]
elif relaxed_units or variable.dtype.kind == 'S':
var_units = _no_units
#--- End: if
# Still here?
return var_units
#--- End: def
def canonical_cell_methods(self, rtol=None, atol=None):
'''
Updates the `_canonical_cell_methods` attribute.
:Parameters:
atol : float
rtol : float
:Returns:
out : cf.CellMethods or None
:Examples:
'''
cell_methods = getattr(self.field, 'cell_methods', None)
if cell_methods is None:
return None
_canonical_cell_methods = self._canonical_cell_methods
for cm in _canonical_cell_methods:
if cell_methods.equivalent(cm, rtol=rtol, atol=atol):
return cm
#--- End: for
# Still here?
_canonical_cell_methods.append(cell_methods)
return cell_methods
#--- End: def
def cell_measure_has_data_and_units(self, msr):
'''
:Parameters:
msr : cf.CellMeasure
:Returns:
out : bool
:Examples:
'''
if not msr.Units:
if self.info:
self.message = \
"%r cell measure has no units" % msr.name('')
return
if not msr._hasData:
if self.info:
self.message = \
"%r cell measure has no data" % msr.name('')
return
return True
#--- End: def
def coord_has_identity_and_data(self, coord):
'''
:Parameters:
coord : cf.Coordinate
:Returns:
out : str or None
The coordinate object's identity, or None if there is no
identity and/or no data.
:Examples:
'''
identity = coord.name(identity=self.strict_identities,
ncvar=self.ncvar_identities)
if identity is None:
# Coordinate has no identity, but it may have a recognised
# axis.
for ctype in ('T', 'X', 'Y', 'Z'):
if getattr(coord, ctype):
identity = ctype
break
#--- End: if
if identity is not None:
all_coord_identities = self.all_coord_identities
if identity in all_coord_identities:
if self.info:
self.message = \
"multiple %r coordinates" % identity
return None
#--- End: if
if coord._hasData or (coord._hasbounds and coord.bounds._hasData):
all_coord_identities.add(identity)
return identity
#--- End: if
if self.info:
self.message = \
"%r coordinate has no identity or no data" % coord.name('')
return None
#--- End: def
def set_ancillary_variables(self):
'''
:Returns:
out : dict or None
:Examples:
'''
f_ancillary_variables = getattr(self.field, 'ancillary_variables',
None)
if f_ancillary_variables is None:
self.ancillary_variables = {}
return True
ancillary_variables = {}
for av in f_ancillary_variables:
identity = av.name(identity=self.strict_identities,
ncvar=self.ncvar_identities)
if identity in ancillary_variables:
if self.info:
self.message = \
"multiple %r ancillary variables" % av.name('')
return None
#--- End: if
ancillary_variables[identity] = av
#--- End: for
self.ancillary_variables = ancillary_variables
return True
#--- End: def
def print_info(self, info, signature=True):
'''
:Parameters:
m : _Meta
info : int
'''
if info >= 2:
if signature:
print 'STRUCTURAL SIGNATURE:\n', self.string_structural_signature()
if self.cell_values:
print 'CANONICAL COORDINATES:\n', self.coordinate_values()
if info >= 3:
print 'COMPLETE AGGREGATION METADATA:\n', self
#--- End: def
def string_structural_signature(self):
'''
'''
keys = ('Identity',
'Units',
'Cell methods',
'Data',
'Properties',
'standard error multiplier',
'valid_min',
'valid_max',
'valid_range',
'Flags',
'Ancillary variables',
'Coordinate reference systems',
'1-d coordinates',
'Dimension coordinates',
'N-d coordinates',
'Cell measures',
)
string = []
# d = {}
for key, value in zip(keys[:], self.signature[:]):
if not (value == () or value is None):
string.append('%s: %r' % (key, value))
# return '{'+'\n'.join(string)+'}'
return '\n'.join(string)
#--- End: def
def structural_signature(self):
'''
:Returns:
out : tuple
:Examples:
'''
f = self.field
# Initialize the structual signature with:
#
# * the identity
# * the canonical units
# * the canonical cell methods
# * whether or not there is a data array
signature = [self.identity, self.units, self.cell_methods, self._hasData]
signature_append = signature.append
# Properties
signature_append(self.properties)
# standard_error_multiplier
signature_append(f.getprop('standard_error_multiplier', None))
# valid_min, valid_max, valid_range
if self.respect_valid:
signature.extend((f.getprop('valid_min' , None),
f.getprop('valid_max' , None),
f.getprop('valid_range', None)))
else:
signature.extend((None, None, None))
# Flags
signature_append(getattr(f, 'Flags', None))
# Add ancillary variables
if self.ancillary_variables:
signature_append(tuple(sorted(self.ancillary_variables)))
else:
signature_append(None)
# Coordinate references
signature_append(tuple(self.coordref_signatures))
# 1-d coordinates for each axis. Note that self.axis_ids has
# already been sorted.
axis = self.axis
x = [(axis[identity]['ids'],
axis[identity]['units'],
axis[identity]['hasbounds'],
axis[identity]['coordrefs']) for identity in self.axis_ids]
signature_append(tuple(x))
# Whether or not each axis has a dimension coordinate
x = [False if axis[identity]['dim_coord_index'] is None else True
for identity in self.axis_ids]
signature_append(tuple(x))
# N-d auxiliary coordinates
nd_aux = self.nd_aux
x = [(identity,
nd_aux[identity]['units'],
nd_aux[identity]['axes'],
nd_aux[identity]['hasbounds'],
nd_aux[identity]['coordrefs']) for identity in sorted(nd_aux)]
signature_append(tuple(x))
# Cell measures
msr = self.msr
x = [(units,
msr[units]['axes']) for units in sorted(msr)]
signature_append(tuple(x))
self.signature = tuple(signature)
#--- End: def
def find_coordrefs(self, key, coord):
'''
:Parameters:
key : str
The domain identifier of the coordinate object
coord : cf.Coordinate
:Returns:
out : tuple or None
:Examples:
>>> dim_coord
<CF DimensionCoordinate: ....>
>>> m.find_coordrefs('dim0', dim_coord)
>>> aux_coord
<CF AuxiliaryCoordinate: ....>
>>> m.find_coordrefs('aux1', aux_coord)
'''
coordrefs = self.coordrefs
if not coordrefs:
return None
# Select the coordinate references which contain a pointer to
# this coordinate
names = [ref.name for ref in coordrefs if key in ref.coords]
if not names:
return None
return tuple(sorted(names))
#--- End: def
#--- End: class
def aggregate(fields,
info=0,
relaxed_units=False,
no_overlap=False,
contiguous=False,
relaxed_identities=False,
ncvar_identities=False,
respect_valid=False,
equal_all=False,
exist_all=False,
equal=None,
exist=None,
ignore=None,
exclude=False,
dimension=(),
concatenate=True,
copy=True,
axes=None,
donotchecknonaggregatingaxes=False,
allow_no_identity=False,
shared_nc_domain=False
):
'''
Aggregate fields into as few fields as possible.
The aggregation of fields may be thought of as the combination fields
into each other to create a new field that occupies a larger domain.
Using the CF aggregation rules, input fields are separated into
aggregatable groups and each group (which may contain just one field)
is then aggregated to a single field. These aggregated fields are
returned in a field list.
**Identities**
In order for aggregation to be possible, fields and their components
need to be unambiguously identifiable. By default, these identities
are taken from `!standard_name` CF properties or else `!id`
attributes. If both of these identifiers are absent then `!long_name`
CF properties or else `!ncvar` attributes may be used if the
*relaxed_identities* parameter is True.
:Parameters:
fields : (sequence of) cf.Field or cf.FieldList
The field or fields to aggregated.
info : int, optional
Print information about the aggregation process. If *info* is
0 then no information is displayed. If *info* is 1 or more
then display information on which fields are unaggregatable,
and why. If *info* is 2 or more then display the structural
signatures of the fields and, when there is more than one
field with the same structural signature, their canonical
first and last coordinate values. If *info* is 3 or more then
display the fields' complete aggregation metadata. By default
*info* is 0 and no information is displayed.
no_overlap : bool, optional
If True then require that aggregated fields have adjacent
dimension coordinate object cells which do not overlap (but
they may share common boundary values). Ignored if the
dimension coordinates objects do not have bounds. See the
*contiguous* parameter.
contiguous : bool, optional
If True then require that aggregated fields have adjacent
dimension coordinate object cells which partially overlap or
share common boundary values. Ignored if the dimension
coordinate objects do not have bounds. See the *no_overlap*
parameter.
relaxed_units : bool, optional
If True then assume that fields or domain items (such as
coordinate objects) with the same identity (as returned by
their `!identity` methods) but missing units all have
equivalent but unspecified units, so that aggregation may
occur. By default such fields are not aggregatable.
allow_no_identity : bool, optional
If True then treat fields with data arrays but with no
identities (see the above notes) as having equal but
unspecified identities, so that aggregation may occur. By
default such fields are not aggregatable.
relaxed_identities : bool, optional
If True then allow fields and their components to be
identified by their `!long_name` CF properties or else
`!ncvar` attributes if their `!standard_name` CF properties or
`!id` attributes are missing.
ncvar_identities : bool, optional
If True then Force fields and their components (such as
coordinates) to be identified by their netCDF file variable
names.
shared_nc_domain : bool, optional
If True then match axes between a field and its contained
ancillary variable and coordinate reference fields via their
netCDF dimension names and not via their domains.
equal_all : bool, optional
If True then require that aggregated fields have the same set
of non-standard CF properties (including
`~cf.Field.long_name`), with the same values. See the
*concatenate* parameter.
equal_ignore : (sequence of) str, optional
Specify CF properties to omit from any properties specified by
or implied by the *equal_all* and *equal* parameters.
equal : (sequence of) str, optional
Specify CF properties for which it is required that aggregated
fields all contain the properties, with the same values. See
the *concatenate* parameter.
exist_all : bool, optional
If True then require that aggregated fields have the same set
of non-standard CF properties (including, in this case,
long_name), but not requiring the values to be the same. See
the *concatenate* parameter.
exist_ignore : (sequence of) str, optional
Specify CF properties to omit from the properties specified by
or implied by the *exist_all* and *exist* parameters.
exist : (sequence of) str, optional
Specify CF properties for which it is required that aggregated
fields all contain the properties, but not requiring the
values to be the same. See the *concatenate* parameter.
respect_valid : bool, optional
If True then the CF properties `~cf.Field.valid_min`,
`~cf.Field.valid_max` and `~cf.Field.valid_range` are taken
into account during aggregation. By default these CF
properties are ignored and are not set in the output fields.
dimension : (sequence of) str, optional
Create new axes for each input field which has one or more of
the given properties. For each CF property name specified, if
an input field has the property then, prior to aggregation, a
new axis is created with an auxiliary coordinate whose datum
is the property's value and the property itself is deleted
from that field.
concatenate : bool, optional
If False then a CF property is omitted from an aggregated
field if the property has unequal values across constituent
fields or is missing from at least one constituent field. By
default a CF property in an aggregated field is the
concatenated collection of the distinct values from the
constituent fields, delimited with the string
``' :AGGREGATED: '``.
copy : bool, optional
If False then do not copy fields prior to aggregation.
Setting this option to False may change input fields in place,
and the output fields may not be independent of the
inputs. However, if it is known that the input fields are
never to accessed again (such as in this case: ``f =
cf.aggregate(f)``) then setting *copy* to False can reduce the
time taken for aggregation.
axes : (sequence of) str, optional
Select axes to aggregate over. Aggregation will only occur
over as large a subset as possible of these axes. Each axis is
identified by the exact identity of a one dimensional
coordinate object, as returned by its `!identity`
method. Aggregations over more than one axis will occur in the
order given. By default, aggregation will be over as many axes
as possible.
donotchecknonaggregatingaxes : bool, optional
If True, and *axes* is set, then checks for consistent data
array values will only be made for one dimensional coordinate
objects which span the any of the given aggregating axes. This
can reduce the time taken for aggregation, but if any those
checks would have failed then this clearly allows the
possibility of an incorrect result. Therefore, this option
should only be used in cases for which it is known that the
non-aggregating axes are in fact already entirely consistent.
:Returns:
out : cf.FieldList
The aggregated fields.
:Examples:
The following six fields comprise eastward wind at two different times
and for three different atmospheric heights for each time:
>>> f
[<CF Field: eastward_wind(latitude(73), longitude(96)>,
<CF Field: eastward_wind(latitude(73), longitude(96)>,
<CF Field: eastward_wind(latitude(73), longitude(96)>,
<CF Field: eastward_wind(latitude(73), longitude(96)>,
<CF Field: eastward_wind(latitude(73), longitude(96)>,
<CF Field: eastward_wind(latitude(73), longitude(96)>]
>>> g = cf.aggregate(f)
>>> g
[<CF Field: eastward_wind(height(3), time(2), latitude(73), longitude(96)>]
>>> g[0].source
'Model A'
>>> g = cf.aggregate(f, dimension=('source',))
[<CF Field: eastward_wind(source(1), height(3), time(2), latitude(73), longitude(96)>]
>>> g[0].source
AttributeError: 'Field' object has no attribute 'source'
'''
# Initialise the cache for coordinate and cell measure hashes,
# first and last values and first and last cell bounds
hfl_cache = _HFLCache()
output_fields = FieldList()
output_fields_append = output_fields.append
if exclude:
exclude = ' NOT'
else:
exclude = ''
atol = ATOL()
rtol = RTOL()
if axes is not None and isinstance(axes, basestring):
axes = (axes,)
# Parse parameters
strict_identities = not (relaxed_identities or ncvar_identities)
if exist_all and equal_all:
raise AttributeError("asdasdas jnf0____")
if equal or exist or ignore:
properties = {'equal' : equal,
'exist' : exist,
'ignore': ignore}
for key, value in properties.iteritems():
if not value:
continue
if isinstance(equal, basestring):
# If it is a string then convert to a single element
# sequence
properties[key] = (value,)
else:
try:
value[0]
except TypeError:
raise TypeError("Bad type of %r parameter: %r" %
(key, type(value)))
#--- End: for
equal = properties['equal']
exist = properties['exist']
ignore = properties['ignore']
if equal and exist:
if set(equal).intersection(exist):
raise AttributeError("888888888888888 asdasdas jnf0____")
if ignore:
ignore = _signature_properties.union(ignore)
else:
ignore = _signature_properties
#--- End: if
unaggregatable = False
status = 0
# ================================================================
# Group together fields with the same structural signature
# ================================================================
signatures = {}
for f in flat(fields):
# ------------------------------------------------------------
# Create the metadata summary, including the structural
# signature
# ------------------------------------------------------------
meta = _Meta(f,
info=info, rtol=rtol, atol=atol,
relaxed_units=relaxed_units,
allow_no_identity=allow_no_identity,
equal_all=equal_all,
exist_all=exist_all,
equal=equal,
exist=exist,
ignore=ignore,
dimension=dimension,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
respect_valid=respect_valid)
if not meta:
unaggregatable = True
status = 1
if info:
print(
"Unaggregatable %r field has%s been output: %s" %
(f.name(''), exclude, meta.message))
if not exclude:
# This field does not have a structural signature, so
# it can't be aggregated. Put it straight into the
# output list and move on to the next input field.
if not copy:
output_fields_append(f)
else:
output_fields_append(f.copy())
#--- End: if
continue
#--- End: if
# ------------------------------------------------------------
# This field has a structural signature, so append it to the
# list of fields with the same structural signature.
# ------------------------------------------------------------
signatures.setdefault(meta.signature, []).append(meta)
#--- End: for
# ================================================================
# Within each group of fields with the same structural signature,
# aggregate as many fields as possible. Sort the signatures so
# that independent aggregations of the same set of input fields
# return fields in the same order.
# ================================================================
for signature in sorted(signatures):
meta = signatures[signature]
if info >= 2:
# Print useful information
meta[0].print_info(info)
print ''
#--- End: if
if len(meta) == 1:
# --------------------------------------------------------
# There's only one field with this signature, so we can
# add it straight to the output list and move on to the
# next signature.
# --------------------------------------------------------
if not copy:
output_fields_append(meta[0].field)
else:
output_fields_append(meta[0].field.copy())
# if info >= 2:
# meta[0].print_info(info)
# if info:
# print(
#"%r field can't be aggregated due to a unique structural signature" %
#meta[0].field.name(''))
continue
#--- End: if
# ------------------------------------------------------------
# Still here? Then there are 2 or more fields with this
# signature which may be aggregatable. These fields need to be
# passed through until no more aggregations are possible. With
# each pass, the number of fields in the group will reduce by
# one for each aggregation that occurs. Each pass represents
# an aggregation in another axis.
# ------------------------------------------------------------
# ------------------------------------------------------------
# For each axis's 1-d coordinates, create the canonical hash
# value and the first and last cell values.
# ------------------------------------------------------------
if axes is None:
# Aggregation will be over as many axes as possible
aggregating_axes = meta[0].axis_ids
_create_hash_and_first_values(meta, None, False, hfl_cache)
#def _create_hash_and_first_values(meta, axes, donotchecknonaggregatingaxes,
# hfl_cache):
else:
# Specific aggregation axes have been selected
aggregating_axes = []
axis_items = meta[0].axis.items()
for axis in axes:
coord = meta[0].field.coord(axis, exact=True)
if coord is None:
continue
coord_identity = coord.name(identity=strict_identities,
ncvar=ncvar_identities)
for identity, value in axis_items:
if (identity not in aggregating_axes and
coord_identity in value['ids']):
aggregating_axes.append(identity)
break
#--- End: for
_create_hash_and_first_values(meta, aggregating_axes,
donotchecknonaggregatingaxes,
hfl_cache)
#--- End: if
if info >= 2:
# Print useful information
for m in meta:
m.print_info(info, signature=False)
print ''
#--- End: if
# Take a shallow copy in case we abandon and want to output
# the original, unaggregated fields.
meta0 = meta[:]
unaggregatable = False
for axis in aggregating_axes:
number_of_fields = len(meta)
if number_of_fields == 1:
break
# --------------------------------------------------------
# Separate the fields with the same structural signature
# into groups such that either within each group the
# fields' domains differ only long the axis or each group
# contains only one field.
#
# Note that the 'a_identity' attribute is set in the
# _group_fields function.
# --------------------------------------------------------
grouped_meta = _group_fields(meta, axis)
if not grouped_meta:
if info:
print(
"Unaggregatable %r fields have%s been output: %s" %
(meta[0].field.name(''), exclude, meta[0].message))
unaggregatable = True
break
#--- End: if
if len(grouped_meta) == number_of_fields:
if info >= 3:
print(
"%r fields can't be aggregated along their %r axis" %
(meta[0].field.name(''), axis))
continue
# --------------------------------------------------------
# Within each group, aggregate as many fields as possible.
# --------------------------------------------------------
for m in grouped_meta:
if len(m) == 1:
continue
# ----------------------------------------------------
# Still here? The sort the fields in place by the
# canonical first values of their 1-d coordinates for
# the aggregating axis.
# ----------------------------------------------------
_sorted_by_first_values(m, axis)
# ----------------------------------------------------
# Check that the aggregating axis's 1-d coordinates
# don't overlap, and don't aggregate anything in this
# group if any do.
# ----------------------------------------------------
if not _ok_coordinate_arrays(m, axis, no_overlap, contiguous,
info):
if info:
print(
"Unaggregatable %r fields have%s been output: %s" %
(m[0].field.name(''), exclude, m[0].message))
unaggregatable = True
break
#--- End: if
# ----------------------------------------------------
# Still here? Then pass through the fields
# ----------------------------------------------------
m0 = m[0].copy()
for m1 in m[1:]:
m0 = _aggregate_2_fields(m0, m1,
rtol=rtol, atol=atol,
respect_valid=respect_valid,
contiguous=contiguous,
no_overlap=no_overlap,
relaxed_units=relaxed_units,
info=info,
concatenate=concatenate,
copy=(copy or not exclude),
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
shared_nc_domain=shared_nc_domain)
if not m0:
# Couldn't aggregate these two fields, so
# abandon all aggregations on the fields with
# this structural signature, including those
# already done.
if info:
print(
"Unaggregatable %r fields have%s been output: %s" %
(m1.field.name(''), exclude, m1.message))
unaggregatable = True
break
#--- End: while
m[:] = [m0]
#--- End: for
if unaggregatable:
break
# --------------------------------------------------------
# Still here? Then the aggregation along this axis was
# completely successful for each sub-group, so reassemble
# the aggregated fields as a single list ready for
# aggregation along the next axis.
# --------------------------------------------------------
meta = [m for gm in grouped_meta for m in gm]
#--- End: for
# Add fields to the output list
if unaggregatable:
# info > 0:
# print ''
status = 1
if not exclude:
if copy:
output_fields.extend((m.field.copy() for m in meta0))
else:
output_fields.extend((m.field for m in meta0))
else:
output_fields.extend((m.field for m in meta))
#--- End: for
aggregate.status = status
if status and info > 0:
print ''
if len(output_fields) == 1:
return output_fields[0]
else:
return output_fields
#--- End: def
# --------------------------------------------------------------------
# Initialise the status
# --------------------------------------------------------------------
aggregate.status = 0
def _create_hash_and_first_values(meta, axes, donotchecknonaggregatingaxes,
hfl_cache):
'''
Updates each field's _Meta object.
:Parameters:
meta : list of _Meta
axes : None or list
donotchecknonaggregatingaxes : bool
:Returns:
None
'''
for m in meta:
domain = m.field.domain
domain_dimensions = domain._axes
m_sort_keys = m.sort_keys
m_sort_indices = m.sort_indices
m_hash_values = m.hash_values
m_first_values = m.first_values
m_last_values = m.last_values
m_id_to_axis = m.id_to_axis
# --------------------------------------------------------
# Create a hash value for each metadata array
# --------------------------------------------------------
# --------------------------------------------------------
# 1-d coordinates
# --------------------------------------------------------
for identity in m.axis_ids:
# print 'identity=', identity #dch
if (axes is not None and donotchecknonaggregatingaxes and
identity not in axes):
x = [None] * len(m.axis[identity]['keys'])
m_hash_values[identity] = x
m_first_values[identity] = x[:]
m_last_values[identity] = x[:]
continue
# Still here?
m_axis_identity = m.axis[identity]
axis = m_id_to_axis[identity]
dim_coord = domain.get(axis, None)
# Find the sort indices for this axis ...
if dim_coord is not None:
# ... which has a dimension coordinate
m_sort_keys[axis] = axis
if not domain.direction(axis):
# Axis is decreasing
sort_indices = slice(None, None, -1)
null_sort = False
else:
# Axis is increasing
sort_indices = slice(None)
null_sort = True
else:
# ... which doesn't have a dimension coordinate but
# does have one or more 1-d auxiliary coordinates
aux = m_axis_identity['keys'][0]
sort_indices = numpy_argsort(domain.get(aux).unsafe_array)
m_sort_keys[axis] = aux
null_sort = False
#-- End: if
m_sort_indices[axis] = sort_indices
hash_values = []
first_values = []
last_values = []
for key, canonical_units in izip(m_axis_identity['keys'],
m_axis_identity['units']):
coord = domain.get(key)
# print repr(coord) #dch
# Get the hash of the data array and its first and
# last values
h, f, l = _get_hfl(coord, canonical_units,
sort_indices, null_sort,
True, False, hfl_cache)
# print h, f, l #dch
first_values.append(f)
last_values.append(l)
if coord._hasbounds:
if coord.isdimension:
# Get the hash of the dimension coordinate
# bounds data array and its first and last
# cell values
hb, fb, lb = _get_hfl(coord.bounds, canonical_units,
sort_indices, null_sort,
False, True, hfl_cache)
m.first_bounds[identity] = fb
m.last_bounds[identity] = lb
else:
# Get the hash of the auxiliary coordinate
# bounds data array
hb = _get_hfl(coord.bounds, canonical_units,
sort_indices, null_sort,
False, False, hfl_cache)
#--- End: if
h = (h, hb)
#--- End: if
hash_values.append(h)
## else:
## coord_units = coord.Units
##
## # Change the coordinate data type if required
## if coord.dtype.char not in ('d', 'S'):
## coord = coord.copy(_only_Data=True)
## coord.dtype = _dtype_float
##
## # Change the coordinate's units to the canonical ones
## coord.Units = canonical_units
##
## # Get the coordinate's data array
## if null_sort:
## array = coord.Data.unsafe_array
## else:
## array = coord.Data.array[sort_indices]
##
## hash_value = hash_array(array)
##
## first_values.append(array.item(0)) #[0])
## last_values.append(array.item(-1)) #[-1])
##
## if coord._hasbounds:
## if null_sort:
## array = coord.bounds.Data.unsafe_array
## else:
## array = coord.bounds.Data.array[sort_indices, ...]
##
## hash_value = (hash_value, hash_array(array))
##
## if key[:3] == 'dim': # can do better than this! DCH
## # Record the bounds of the first and last
## # (sorted) cells of a dimension coordinate
## # (don't need to do this for an auxiliary
## # coordinate).
## array0 = array[0, ...].copy()
## array0.sort()
## m.first_bounds[identity] = array0
##
## array0 = array[-1, ...].copy()
## array0.sort()
## m.last_bounds[identity] = array0
## #--- End: if
##
## hash_values.append(hash_value)
##
## # Reinstate the coordinate's original units
## coord.Units = coord_units
#--- End: for
m_hash_values[identity] = hash_values
m_first_values[identity] = first_values
m_last_values[identity] = last_values
#--- End: for
# ------------------------------------------------------------
# N-d auxiliary coordinates
# ------------------------------------------------------------
if donotchecknonaggregatingaxes:
for aux in m.nd_aux.itervalues():
aux['hash_value'] = None
else:
for aux in m.nd_aux.itervalues():
key = aux['key']
canonical_units = aux['units']
coord = domain.get(key)
axes = [m_id_to_axis[identity] for identity in aux['axes']]
domain_axes = domain_dimensions[key]
if axes != domain_axes:
coord = coord.copy(_only_Data=True)
iaxes = [domain_axes.index(axis) for axis in axes]
coord.transpose(iaxes, i=True)
#--- End: if
sort_indices = tuple([m_sort_indices[axis] for axis in axes])
# Get the hash of the data array
h = _get_hfl(coord, canonical_units, sort_indices,
False, False, False, hfl_cache)
if coord._hasbounds:
# Get the hash of the bounds data array
hb = _get_hfl(coord.bounds, canonical_units,
sort_indices,
False, False, False, hfl_cache)
h = (h, hb)
#--- End: if
aux['hash_value'] = h
## else:
## coord_units = coord.Units
##
## # Change the coordinate data type if required
## if coord.dtype.char not in ('d', 'S'):
## coord = coord.copy(_only_Data=True)
## coord.dtype = _dtype_float
## copied = True
## else:
## copied = False
##
## # Change the coordinate's units to the canonical ones
## coord.Units = aux['units'] #canonical_units
##
## # Get the coordinate's data array
## array = coord.Data.array[sort_indices]
##
## hash_value = hash_array(array)
##
## if coord._hasbounds:
## sort_indices.append(Ellipsis)
## array = coord.bounds.Data.array[sort_indices]
## hash_value = (hash_value, hash_array(array))
##
## aux['hash_value'] = hash_value
##
## # Reinstate the coordinate's original units
## coord.Units = coord_units
#--- End: for
#--- End: if
# ------------------------------------------------------------
# Cell measures
# ------------------------------------------------------------
if donotchecknonaggregatingaxes:
for msr in m.msr.itervalues():
msr['hash_values'] = [None] * len(msr['keys'])
else:
for canonical_units, msr in m.msr.iteritems():
hash_values = []
for key, axes in izip(msr['keys'], msr['axes']):
coord = domain.get(key)
axes = [m_id_to_axis[identity] for identity in axes]
domain_axes = domain_dimensions[key]
if axes != domain_axes:
coord = coord.copy(_only_Data=True)
iaxes = [domain_axes.index(axis) for axis in axes]
coord.transpose(iaxes, i=True)
#--- End: if
sort_indices = [m_sort_indices[axis] for axis in axes]
## if qwerty:
# Get the hash of the data array
h = _get_hfl(coord, canonical_units,
tuple(sort_indices),
False, False, False, hfl_cache)
hash_values.append(h)
## else:
## coord_units = coord.Units
##
## # Change the coordinate data type if required
## if coord.dtype.char not in ('d', 'S'):
## coord = coord.copy(_only_Data=True)
## coord.dtype = _dtype_float
## copied = True
## else:
## copied = False
##
## # Change the coordinate's units to the canonical ones
## coord.Units = canonical_units
##
## array = coord.Data.array[tuple(sort_indices)]
##
## hash_values.append(hash_array(array))
##
## # Reinstate the coordinate's original units
## coord.Units = coord_units
#--- End: for
msr['hash_values'] = hash_values
#--- End: for
#--- End: if
# m.calculate_hash_values = set()
m.cell_values = True
#--- End: for
#--- End: def
def _get_hfl(v, canonical_units, sort_indices, null_sort,
first_and_last_values, first_and_last_bounds,
hfl_cache):
'''
Return the hash value, and optionally first and last values (or cell
bounds)
'''
create_hash = True
create_fl = first_and_last_values
create_flb = first_and_last_bounds
key = None
d = v.Data
if d._pmsize == 1:
partition = d.partitions.matrix.item()
if not partition.part:
key = getattr(partition.subarray, 'file_pointer', None)
if key is not None:
hash_value = hfl_cache.hash.get(key, None)
create_hash = hash_value is None
if first_and_last_values:
first, last = hfl_cache.fl.get(key, (None, None))
create_fl = first is None
if first_and_last_bounds:
first, last = hfl_cache.flb.get(key, (None, None))
create_flb = first is None
#--- End: if
if create_hash or create_fl or create_flb:
# Change the data type if required
if d.dtype.char not in ('d', 'S'):
d = d.copy()
d.dtype = _dtype_float
# Change the units to the canonical ones
units = d.Units
d.Units = canonical_units
# Get the data array
if null_sort:
array = d.unsafe_array
else:
array = d.array[sort_indices]
# Reinstate the original units
d.Units = units
if create_hash:
# if v.standard_name=='latitude':
# print repr(array)
# print array.dtype
hash_value = hash_array(array)
hfl_cache.hash[key] = hash_value
if create_fl:
first = array.item(0)
last = array.item(-1)
hfl_cache.fl[key] = (first, last)
if create_flb:
# Record the bounds of the first and last (sorted) cells
first = numpy_sort(array[0, ...])
last = numpy_sort(array[-1, ...])
hfl_cache.flb[key] = (first, last)
#--- End: if
if first_and_last_values or first_and_last_bounds:
return hash_value, first, last
else:
return hash_value
#--- End: def
def _group_fields(meta, axis):
'''
:Parameters:
meta : list of _Meta
axis : str
The name of the axis to group for aggregation.
:Returns:
out : list of cf.FieldList
'''
axes = meta[0].axis_ids
if axes:
if axis in axes:
# Move axis to the end of the axes list
axes = axes[:]
axes.remove(axis)
axes.append(axis)
#--- End: if
sort_by_axis_ids = itemgetter(*axes)
def _hash_values(m):
return sort_by_axis_ids(m.hash_values)
meta.sort(key=_hash_values)
#--- End: if
# Create a new group of potentially aggregatable fields (which
# contains the first field in the sorted list)
m0 = meta[0]
groups_of_fields = [[m0]]
hash0 = m0.hash_values
for m0, m1 in izip(meta[:-1], meta[1:]):
#-------------------------------------------------------------
# Count the number of axes which are different between the two
# fields
# -------------------------------------------------------------
count = 0
hash1 = m1.hash_values
for identity, value in hash0.iteritems():
if value != hash1[identity]:
count += 1
a_identity = identity
#--- End: for
hash0 = hash1
if count == 1:
# --------------------------------------------------------
# Exactly one axis has different 1-d coordinate values
# --------------------------------------------------------
if a_identity != axis:
# But it's not the axis that we're trying currently to
# aggregate over
groups_of_fields.append([m1])
continue
# Still here? Then it is the axis that we're trying
# currently to aggregate over.
ok = True
# Check the N-d auxiliary coordinates
for identity, aux0 in m0.nd_aux.iteritems():
if (a_identity not in aux0['axes'] and
aux0['hash_value'] != m1.nd_aux[identity]['hash_value']):
# This matching pair of N-d auxiliary coordinates
# does not span the aggregating axis and they have
# different data array values
ok = False
break
#--- End: for
if not ok:
groups_of_fields.append([m1])
continue
# Still here? Then check the cell measures
msr0 = m0.msr
for units in msr0:
for axes, hash_value0, hash_value1 in izip(
msr0[units]['axes'],
msr0[units]['hash_values'],
m1.msr[units]['hash_values']):
if a_identity not in axes and hash_value0 != hash_value1:
# There is a matching pair of cell measures
# with these units which does not span the
# aggregating axis and they have different
# data array values
ok = False
break
#--- End: for
if not ok:
groups_of_fields.append([m1])
continue
# Still here? Then set the identity of the aggregating
# axis
m0.a_identity = a_identity
m1.a_identity = a_identity
# Append field1 to this group of potentially aggregatable
# fields
groups_of_fields[-1].append(m1)
elif not count:
# --------------------------------------------------------
# Zero axes have different 1-d coordinate values, so don't
# aggregate anything in this entire group.
# --------------------------------------------------------
meta[0].message = \
"indistinguishable coordinates or other domain information"
return ()
else:
# --------------------------------------------------------
# Two or more axes have different 1-d coordinate values,
# so create a new sub-group of potentially aggregatable
# fields which contains field1.
# --------------------------------------------------------
groups_of_fields.append([m1])
#--- End: if
#--- End: for
return groups_of_fields
#--- End: def
def _sorted_by_first_values(meta, axis):
'''
Sort fields inplace
:Parameters:
meta : list of _Meta
axis : str
:Returns:
None
'''
sort_by_axis_ids = itemgetter(axis)
def _first_values(m):
return sort_by_axis_ids(m.first_values)
#--- End: def
meta.sort(key=_first_values)
#--- End: def
def _ok_coordinate_arrays(meta, axis, no_overlap, contiguous, info):
'''
Return True if the aggregating axis's 1-d coordinates are all
aggregatable.
It is assumed that the input metadata objects have already been sorted
by the canonical first values of their 1-d coordinates.
:Parameters:
meta : list of _Meta
axis : str
Find the canonical identity of the aggregating axis.
no_overlap : bool
See the `aggregate` function for details.
contiguous : bool
See the `aggregate` function for details.
NOT : str
:Returns:
out : bool
:Examples:
>>> if not _ok_coordinate_arrays(meta, True, False)
... print "Don't aggregate"
'''
m = meta[0]
dim_coord_index = m.axis[axis]['dim_coord_index']
if dim_coord_index is not None:
# ------------------------------------------------------------
# The aggregating axis has a dimension coordinate
# ------------------------------------------------------------
# Check for overlapping dimension coordinate cell centres
dim_coord_index0 = dim_coord_index
for m0, m1 in izip(meta[:-1], meta[1:]):
dim_coord_index1 = m1.axis[axis]['dim_coord_index']
if (m0.last_values[axis][dim_coord_index0] >=
m1.first_values[axis][dim_coord_index1]):
# Found overlap
if info:
meta[0].message = \
"%r dimension coordinate values overlap (%s >= %s)" % \
(m.axis[axis]['ids'][dim_coord_index],
m0.last_values[axis][dim_coord_index0],
m1.first_values[axis][dim_coord_index1])
#
#
#"%r fields can't be aggregated due to their %r dimension coordinate values over#lapping (%s >= %s)" %
#(m.field.name(''),
# m.axis[axis]['ids'][dim_coord_index],
# m0.last_values[axis][dim_coord_index0],
# m1.first_values[axis][dim_coord_index1]))
return
dim_coord_index0 = dim_coord_index1
#--- End: for
if axis in m.first_bounds:
# --------------------------------------------------------
# The dimension coordinates have bounds
# --------------------------------------------------------
if no_overlap:
for m0, m1 in izip(meta[:-1], meta[1:]):
if (m1.first_bounds[axis][0] <
m0.last_bounds[axis][1]):
# Do not aggregate anything in this group
# because overlapping has been disallowed and
# the first cell from field1 overlaps with the
# last cell from field0.
if info:
meta[0].message = \
"%r dimension coordinate bounds values overlap (%s < %s)" % \
(m.axis[axis]['ids'][dim_coord_index],
m1.first_bounds[axis][0],
m0.last_bounds[axis][1])
# print(
#"%r fields can't be aggregated due to their %r dimension coordinate bounds valu#es overlapping (%s < %s)" %
#(m.field.name(''),
# m.axis[axis]['ids'][dim_coord_index],
# m1.first_bounds[axis][0],
# m0.last_bounds[axis][1]
# ))
return
#--- End: for
else:
for m0, m1 in izip(meta[:-1], meta[1:]):
m0_last_bounds = m0.last_bounds[axis]
m1_first_bounds = m1.first_bounds[axis]
if (m1_first_bounds[0] <= m0_last_bounds[0] or
m1_first_bounds[1] <= m0_last_bounds[1]):
# Do not aggregate anything in this group
# because, even though overlapping has been
# allowed, the first cell from field1 overlaps
# in an unreasonable way with the last cell
# from field0.
if info:
meta[0].message = \
"%r dimension coordinate bounds values overlap by too much (%s <= %s)" % \
(m.axis[axis]['ids'][dim_coord_index],
m1_first_bounds[0], m0_last_bounds[0],
m1_first_bounds[1], m0_last_bounds[1])
# print(
#"%r fields can't be aggregated due to their %r dimension coordinate bounds valu#es overlapping by too much (%s <= %s)" %
#(m.field.name(''),
# m.axis[axis]['ids'][dim_coord_index],
# m1_first_bounds[0], m0_last_bounds[0],
# m1_first_bounds[1], m0_last_bounds[1]
# ))
return
#--- End: for
#--- End: if
if contiguous:
for m0, m1 in izip(meta[:-1], meta[1:]):
if (m0.last_bounds[axis][1] <
m1.first_bounds[axis][0]):
# Do not aggregate anything in this group
# because contiguous coordinates have been
# specified and the first cell from field1 is
# not contiguous with the last cell from
# field0.
if info:
meta[0].message = \
"%r dimension coordinate cells are not contiguous (%s < %s)" % \
(m.axis[axis]['ids'][dim_coord_index],
m0.last_bounds[axis][1],
m1.first_bounds[axis][0])
# print(
#"%r fields can't be aggregated due to their %r dimension coordinate cells not b#eing contiguous (%s < %s)" %
#(m.field.name(''),
# m.axis[axis]['ids'][dim_coord_index],
# m0.last_bounds[axis][1],
# m1.first_bounds[axis][0]
# ))
return
#--- End: for
#--- End: if
#--- End: if
else:
# ------------------------------------------------------------
# The aggregating axis does not have a dimension coordinate,
# but it does have at least one 1-d auxiliary coordinate.
# ------------------------------------------------------------
# Check for duplicate auxiliary coordinate values
for i, identity in enumerate(meta[0].axis[axis]['ids']):
set_of_1d_aux_coord_values = set()
number_of_1d_aux_coord_values = 0
for m in meta:
aux = m.axis[axis]['keys'][i]
array = m.field.domain.get(aux).array
set_of_1d_aux_coord_values.update(array)
number_of_1d_aux_coord_values += array.size
if len(set_of_1d_aux_coord_values) != number_of_1d_aux_coord_values:
if info:
meta[0].message = \
"no %r dimension coordinates and %r auxiliary coordinates have duplicate values" % \
(identity, identity)
# print(
#"%r fields can't be aggregated due to their %r axes having no dimension coordin#ates and their %r auxiliary coordinates have duplicate values" %
#(m.field.name(''),
# identity,
# identity))
return
#--- End: for
#--- End: for
#--- End: if
# ----------------------------------------------------------------
# Still here? Then the aggregating axis does not overlap between
# any of the fields.
# ----------------------------------------------------------------
return True
#--- End: def
def _aggregate_2_fields(m0, m1,
rtol=None, atol=None,
info=0,
respect_valid=False,
relaxed_units=False,
no_overlap=False,
contiguous=False,
concatenate=True,
copy=True,
relaxed_identities=False,
ncvar_identities=False,
shared_nc_domain=False):
'''
:Parameters:
m0 : _Meta
m1 : _Meta
contiguous : bool, optional
See the `aggregate` function for details.
rtol : float, optional
See the `aggregate` function for details.
atol : float, optional
See the `aggregate` function for details.
info : int, optional
See the `aggregate` function for details.
no_overlap : bool, optional
See the `aggregate` function for details.
relaxed_units : bool, optional
See the `aggregate` function for details.
relaxed_identities : bool, optional
See the `aggregate` function for details.
ncvar_identities : bool, optional
See the `aggregate` function for details.
:Returns:
out : _Meta or bool
'''
# if copy and not m0.aggregated_field:
# m0.field = m0.field.copy()
a_identity = m0.a_identity
# ----------------------------------------------------------------
# Aggregate coordinate references
# ----------------------------------------------------------------
if m0.coordref_signatures:
t = _aggregate_coordrefs(m0, m1,
axis=a_identity,
rtol=rtol, atol=atol,
respect_valid=respect_valid,
relaxed_units=relaxed_units,
no_overlap=no_overlap, info=info,
contiguous=contiguous,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
shared_nc_domain=shared_nc_domain)
if not t:
return
else:
t = None
# ----------------------------------------------------------------
# Aggregate ancillary variables
# ----------------------------------------------------------------
if m0.ancillary_variables:
av = _aggregate_ancillary_variables(m0, m1,
axis=a_identity,
rtol=rtol, atol=atol,
respect_valid=respect_valid,
relaxed_units=relaxed_units,
no_overlap=no_overlap,
info=info,
contiguous=contiguous,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
shared_nc_domain=shared_nc_domain)
if not av:
return
else:
av = None
# Still here?
field0 = m0.field
field1 = m1.field
if copy:
field1 = field1.copy()
domain0 = field0.domain
domain1 = field1.domain
if t:
# ------------------------------------------------------------
# Update coordinate references
# ------------------------------------------------------------
for key, ref in t.iteritems():
domain0.insert_ref(ref, key=key, copy=False, replace=True)
#--- End: if
if av:
# ------------------------------------------------------------
# Update ancillary variables
# ------------------------------------------------------------
field0.ancillary_variables = av
# ----------------------------------------------------------------
# Map the axes of field1 to those of field0
# ----------------------------------------------------------------
dim1_name_map = {}
for identity in m0.axis_ids:
dim1_name_map[m1.id_to_axis[identity]] = m0.id_to_axis[identity]
dim0_name_map = {}
for axis1, axis0 in dim1_name_map.iteritems():
dim0_name_map[axis0] = axis1
# ----------------------------------------------------------------
# In each field, find the identifier of the aggregating axis.
# ----------------------------------------------------------------
adim0 = m0.id_to_axis[a_identity]
adim1 = m1.id_to_axis[a_identity]
# ----------------------------------------------------------------
# Make sure that, along the aggregating axis, field1 runs in the
# same direction as field0
# ----------------------------------------------------------------
direction0 = domain0.direction(adim0)
if domain1.direction(adim1) != direction0:
field1.flip(adim1, i=True)
# ----------------------------------------------------------------
# Find matching pairs of coordinates and cell measures which span
# the aggregating axis
# ----------------------------------------------------------------
# 1-d coordinates
spanning_variables = [(key0, key1, domain0.get(key0), domain1.get(key1))
for key0, key1 in izip(m0.axis[a_identity]['keys'],
m1.axis[a_identity]['keys'])]
hash_values0 = m0.hash_values[a_identity]
hash_values1 = m1.hash_values[a_identity]
for i, (hash0, hash1) in enumerate(izip(hash_values0, hash_values1)):
try:
hash_values0[i].append(hash_values1[i])
except AttributeError:
hash_values0[i] = [hash_values0[i], hash_values1[i]]
#--- End: for
# N-d auxiliary coordinates
for identity in m0.nd_aux:
aux0 = m0.nd_aux[identity]
aux1 = m1.nd_aux[identity]
if a_identity in aux0['axes']:
key0 = aux0['key']
key1 = aux1['key']
spanning_variables.append((key0, key1,
domain0.get(key0),
domain1.get(key1)))
hash_value0 = aux0['hash_value']
hash_value1 = aux1['hash_value']
try:
hash_value0.append(hash_value1)
except AttributeError:
aux0['hash_value'] = [hash_value0, hash_value1]
#--- End: for
# Cell measures
for units in m0.msr:
hash_values0 = m0.msr[units]['hash_values']
hash_values1 = m1.msr[units]['hash_values']
for i, (axes, key0, key1) in enumerate(izip(m0.msr[units]['axes'],
m0.msr[units]['keys'],
m1.msr[units]['keys'])):
if a_identity in axes:
spanning_variables.append((key0, key1,
domain0.get(key0),
domain1.get(key1)))
try:
hash_values0[i].append(hash_values1[i])
except AttributeError:
hash_values0[i] = [hash_values0[i], hash_values1[i]]
#--- End: for
# ----------------------------------------------------------------
# For each matching pair of coordinates and cell measures which
# span the aggregating axis, insert the one from field1 into the
# one from field0
# ----------------------------------------------------------------
domain_axes = domain0._axes
for key0, key1, item0, item1 in spanning_variables:
item_axes0 = domain0.item_axes(key0)
item_axes1 = domain1.item_axes(key1)
# Ensure that the axis orders are the same in both items
iaxes = [item_axes1.index(dim0_name_map[axis0]) for axis0 in item_axes0]
item1.transpose(iaxes, i=True)
# Find the position of the concatenating axis
axis = item_axes0.index(adim0)
if direction0:
# The fields are increasing along the aggregating axis
item0.Data = Data.concatenate((item0.Data, item1.Data), axis,
_preserve=False)
if item0._hasbounds:
item0.bounds.Data = Data.concatenate((item0.bounds.Data,
item1.bounds.Data),
axis, _preserve=False)
else:
# The fields are decreasing along the aggregating axis
item0.Data = Data.concatenate((item1.Data, item0.Data), axis,
_preserve=False)
if item0._hasbounds:
item0.bounds.Data = Data.concatenate((item1.bounds.Data,
item0.bounds.Data),
axis, _preserve=False)
#--- End: for
# ----------------------------------------------------------------
# Insert the data array from field1 into the data array of field0
# ----------------------------------------------------------------
if m0._hasData:
data_axes0 = domain0.data_axes()
data_axes1 = domain1.data_axes()
# Ensure that both data arrays span the same axes, including
# the aggregating axis.
for axis1 in data_axes1:
axis0 = dim1_name_map[axis1]
if axis0 not in data_axes0:
field0.expand_dims(0, axis0, i=True)
data_axes0.append(axis0)
for axis0 in data_axes0:
axis1 = dim0_name_map[axis0]
if axis1 not in data_axes1:
field1.expand_dims(0, axis1, i=True)
# Find the position of the concatenating axis
if adim0 not in data_axes0:
# Insert the aggregating axis at position 0 because is not
# already spanned by either data arrays
field0.expand_dims(0, adim0, i=True)
field1.expand_dims(0, adim1, i=True)
axis = 0
else:
axis = data_axes0.index(adim0)
# Ensure that the axis orders are the same in both fields
transpose_axes1 = [dim0_name_map[axis0] for axis0 in data_axes0]
if transpose_axes1 != data_axes1:
field1.transpose(transpose_axes1, i=True)
if direction0:
# The fields are increasing along the aggregating axis
field0.Data = Data.concatenate((field0.Data, field1.Data), axis,
_preserve=False)
else:
# The fields are decreasing along the aggregating axis
field0.Data = Data.concatenate((field1.Data, field0.Data), axis,
_preserve=False)
#--- End: if
# Update the size of the aggregating axis in field0
domain0._axes_sizes[adim0] += domain1._axes_sizes[adim1]
# Make sure that field0 has a standard_name, if possible.
if getattr(field0, 'id', None) is not None:
standard_name = field1.getprop('standard_name', None)
if standard_name is not None:
field0.standard_name = standard_name
del field0.id
#--- End: if
#-----------------------------------------------------------------
# Update the properties in field0
#-----------------------------------------------------------------
for prop in set(field0._simple_properties()) | set(field1._simple_properties()):
value0 = field0.getprop(prop, None)
value1 = field1.getprop(prop, None)
if prop in ('valid_min', 'valid_max', 'valid_range'):
if not m0.respect_valid:
try:
field0.delprop(prop)
except AttributeError:
pass
#--- End: if
continue
#--- End: if
if prop == '_FillValue' or prop == 'missing_value':
continue
# Still here?
if equals(value0, value1):
continue
if concatenate:
if value1 is not None:
if value0 is not None:
field0.setprop(prop, '%s :AGGREGATED: %s' % (value0, value1))
else:
field0.setprop(prop, ' :AGGREGATED: %s' % value1)
else:
if value0 is not None:
field0.delprop(prop)
#--- End: for
#-----------------------------------------------------------------
# Update the attributes in field0
#-----------------------------------------------------------------
for attr in m0.attributes | m1.attributes:
value0 = getattr(field0, attr, None)
value1 = getattr(field1, attr, None)
if equals(value0, value1):
continue
if concatenate:
if value1 is not None:
if value0 is not None:
setattr(field0, attr, '%s :AGGREGATED: %s' % (value0, value1))
else:
setattr(field0, attr, ' :AGGREGATED: %s' % value1)
else:
m0.attributes.discard(attr)
if value0 is not None:
delattr(field0, attr)
#--- End: for
# Note that the field in this _Meta object has already been
# aggregated
m0.aggregated_field = True
# ----------------------------------------------------------------
# Return the _Meta object containing the aggregated field
# ----------------------------------------------------------------
return m0
#--- End: def
def _aggregate_coordrefs(m0, m1,
axis=None,
rtol=None, atol=None,
respect_valid=False,
relaxed_units=False,
no_overlap=False,
info=0,
contiguous=False,
relaxed_identities=False,
ncvar_identities=False,
shared_nc_domain=False):
'''
Aggregate fields in coordinate references.
:Parameters:
m0 : _Meta
m1 : _Meta
no_overlap : bool, optional
See the `aggregate` function for details.
contiguous : bool, optional
See the `aggregate` function for details.
rtol : float, optional
See the `aggregate` function for details.
atol : float, optional
See the `aggregate` function for details.
info : int, optional
See the `aggregate` function for details.
relaxed_units : bool, optional
See the `aggregate` function for details.
:Returns:
out : dict
'''
# axis = m0.a_identity
field0 = m0.field
field1 = m1.field
out = {}
for signature in m0.coordref_signatures:
name = signature[0]
key, coordref0 = field0.refs(name, exact=True).popitem()
coordref1 = field1.ref(name, exact=True)
# Initialize the new coordinate reference
new_coordref = CoordinateReference(name=name)
for term in set(coordref0).union(coordref1):
value0 = coordref0.get(term, None)
value1 = coordref1.get(term, None)
if value1 is None and value0 is None:
# ----------------------------------------------------
# Both terms are undefined
# ----------------------------------------------------
continue
if value1 is None:
t, u, m, value = coordref0, coordref1, m0, value0
elif value0 is None:
t, u, m, value = coordref1, coordref0, m1, value1
else:
t = None
if t is not None:
# ----------------------------------------------------
# Exactly one term is undefined
# ----------------------------------------------------
if term in t.coord_terms:
# Term is a coordinate
value = m.field.item(t[term], exact=True)
if value is None:
continue
#--- End: if
default = t.default_value(term)
if default is None:
if info:
m1.message = \
"%r %s %r parameter has no default value" % (name, t.type, term)
return
if isinstance(value, Field):
x = _Meta(value, info=info,
relaxed_units=relaxed_units,
allow_no_identity=True,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
respect_valid=respect_valid)
if not x:
if info:
m1.message = \
"%r %s %r parameter is a field with no structural signature" % \
(name, t.type, term)
return
#--- End: if
if not allclose(value, default, rtol=rtol, atol=atol):
if info:
m1.message = \
"%r %s %r parameters have non-equivalent values" % (name, t.type, term)
return
# Update the new coordinate reference
if term in t.coord_terms:
new_coordref.setcoord(term, t[term])
else:
new_coordref[term] = value
continue
else:
t = coordref0
#--- End: if
coord0 = term in coordref0.coord_terms
coord1 = term in coordref1.coord_terms
if coord0 and coord1:
# ----------------------------------------------------
# Both terms are coordinates
# ----------------------------------------------------
coord0 = field0.item(value0, exact=True)
coord1 = field1.item(value1, exact=True)
coord0_name = coord0.name(identity=m0.strict_identities,
ncvar=m0.ncvar_identities)
coord1_name = coord1.name(identity=m1.strict_identities,
ncvar=m1.ncvar_identities)
if (coord0 is None or
coord1 is None or
coord0_name != coord1_name):
if info:
m1.message = \
"%r %s %r parameters are unaggregatable coordinates" % \
(name, t.type, term)
return
# Update the new coordinate reference
new_coordref.setcoord(term, value0)
continue
if coord0 or coord1:
# ----------------------------------------------------
# Exactly one term is a coordinate
# ----------------------------------------------------
if info:
m1.message = \
"%r %s %r parameters are not all coordinates" % (name, t.type, term)
return
is_field0 = isinstance(value0, Field)
is_field1 = isinstance(value1, Field)
if not is_field0 and not is_field1:
# ----------------------------------------------------
# Neither term is a field
# ----------------------------------------------------
if not allclose(value0, value1, rtol=rtol, atol=atol):
# The values are not equivalent
if info:
m1.message = \
"%r %s %r parameters have non-equivalent values" % (name, t.type, term)
return
# Update the new coordinate reference
new_coordref[term] = value0
continue
if is_field0 != is_field1:
# ----------------------------------------------------
# Exactly one term is a field
# ----------------------------------------------------
if info:
m1.message = \
"%r %s %r parameters are not all fields" % (name, t.type, term)
return
# --------------------------------------------------------
# Both terms are fields
# --------------------------------------------------------
if shared_nc_domain:
role = '%r %s %r' % (name, t.type, term)
value0, message0 = _share_nc_domain(value0, field0, role)
if message0:
if info:
m0.message = message0
return
#--- End: if
value1, message1 = _share_nc_domain(value1, field1, role)
if message1:
if info:
m1.message = message1
return
#--- End: if
#--- End: if
x0 = _Meta(value0, info=info,
relaxed_units=relaxed_units,
allow_no_identity=True,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
respect_valid=respect_valid)
x1 = _Meta(value1, info=info,
relaxed_units=relaxed_units,
allow_no_identity=True,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
respect_valid=respect_valid)
if not (x0 and x1):
# At least one field doesn't have a structual
# signature
if info:
m1.message = \
"%r %s %r parameter is a field with no structural signature" % \
(name, t.type, term)
return
#--- End: if
if axis not in x0.axis and axis not in x1.axis:
# Neither field spans the aggregating axis ...
if value0.equivalent_data(value1, rtol=rtol, atol=atol):
# ... and the fields have equivalent data
# arrays. Therefore we don't need to do any
# aggregation.
# Update the new coordinate reference
new_coordref[term] = value0
continue
else:
# ... and the fields do not have equivalent data
if info:
m1.message = \
"%r %s %r parameters are fields with non-equivalent values" % \
(name, t.type, term)
return
#--- End: if
if not (axis in x0.axis and axis in x1.axis):
# Only one of the fields spans the aggregating axis
if info:
m1.message = \
"%r %s %r parameters are unaggregatable fields" % (name, t.type, term)
# print(
#"%r fields can't be aggregated due to their %r %s %r parameters being fields wh#ich are not aggregatable" %
#(field0.name(''), name, t.type, term))
return
#--- End: if
# Both fields span the aggregating axis, so try to
# aggregate them.
new_value = aggregate((value0, value1),
info=info,
no_overlap=no_overlap,
contiguous=contiguous,
respect_valid=respect_valid,
relaxed_units=relaxed_units,
allow_no_identity=True,
axes=axis,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities)
if len(new_value) == 2:
# Couldn't aggregate them (because we got two fields
# back instead of one)
if info:
m1.message = \
"%r %s %r parameters are unaggregatable fields" % (name, t.type, term)
# print(
#"%r fields can't be aggregated due to their %r %s %r parameters being fields wh#ich are not aggregatable" %
#(field0.name(''), name, t.type, term))
return
#--- End: if
# Successfully aggregated the coordinate reference fields
coordref0[term] = new_value[0] # DCH: Why?????????
# Update the new coordinate reference
new_coordref[term] = new_value[0]
#---End: for
out[key] = new_coordref
#---End: for
return out
#--- End: def
def _aggregate_ancillary_variables(m0, m1,
axis=None,
rtol=None, atol=None,
respect_valid=False,
relaxed_units=False,
no_overlap=False,
info=0,
contiguous=False,
relaxed_identities=False,
ncvar_identities=False,
shared_nc_domain=False):
'''
Aggregate the ancillary variable fields.
:Parameters:
m0 : _Meta
m1 : _Meta
no_overlap : bool, optional
See the `aggregate` function for details.
contiguous : bool, optional
See the `aggregate` function for details.
rtol : float, optional
See the `aggregate` function for details.
atol : float, optional
See the `aggregate` function for details.
info : int, optional
See the `aggregate` function for details.
relaxed_units : bool, optional
See the `aggregate` function for details.
relaxed_identities : bool, optional
See the `aggregate` function for details.
ncvar_identities : bool, optional
See the `aggregate` function for details.
:Returns:
out : cf.FieldList or bool
'''
field0 = m0.field
field1 = m1.field
ancillary_variables = m0.ancillary_variables
# new_ancillary_variables = AncillaryVariables()
new_ancillary_variables = FieldList()
for identity, ancil0 in ancillary_variables.iteritems():
ancil1 = m1.ancillary_variables[identity]
if shared_nc_domain:
ancil0, message0 = _share_nc_domain(ancil0, field0, 'ancillary variable')
if message0:
if info:
m0.message = message0
return
#--- End: if
ancil1, message1 = _share_nc_domain(ancil1, field1, 'ancillary variable')
if message1:
if info:
m1.message = message1
return
#--- End: if
#--- End: if
x0 = _Meta(ancil0, info=info, relaxed_units=relaxed_units,
allow_no_identity=False,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
respect_valid=respect_valid)
x1 = _Meta(ancil1, info=info, relaxed_units=relaxed_units,
allow_no_identity=False,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities,
respect_valid=respect_valid)
if not (x0 and x1):
# At least one field doesn't have a structual signature
if info:
m1.message = \
"%r ancillary variable is a field with no structural signature" % \
ancil0.name('')
return
#--- End: if
if axis not in x0.axis and axis not in x1.axis:
# Neither field spans the aggregating axis ...
if ancil0.equivalent_data(ancil1, rtol=rtol, atol=atol,
traceback=False):
# ... and the fields are equivalent
new_ancillary_variables.append(ancil0)
continue
else:
# ... and the fields are not equivalent
if info:
m1.message = \
"2 %r ancillary variable fields have non-equivalent values" % ancil0.name('')
return
#--- End: if
# Still here?
if not (axis in x0.axis and axis in x1.axis):
if info:
m1.message = \
"3 %r ancillary variable fields are unaggregatable" % ancil0.name('')
return
#--- End: if
# Both fields span the aggregating axis
if (ancil0.axis_size(axis, exact=True) == 1 and
ancil1.axis_size(axis, exact=True) == 1 and
field0.axis_size(axis, exact=True) > 1 or
field1.axis_size(axis, exact=True) > 1):
# The aggregating axis has size 1 in both ancillary fields
# and size > 1 in at least one parent field
if ancil0.equivalent(ancil1, rtol=rtol, atol=atol):
ancillary_variables[identity] = ancil0 ### WHY??
new_ancillary_variables.append(ancil0)
continue
#--- End: if
# Still here? Then try to aggregate the ancillary fields.
new_value = aggregate((ancil0, ancil1), info=info,
no_overlap=no_overlap, contiguous=contiguous,
respect_valid=respect_valid,
relaxed_units=relaxed_units,
allow_no_identity=True,
axes=axis,
relaxed_identities=relaxed_identities,
ncvar_identities=ncvar_identities)
if len(new_value) == 2:
# We got two fields back instead of one, therefore they
# couldn't be aggregated.
if info:
m1.message = \
"4 %r ancillary variable fields are unaggregatable" % ancil0.name('')
return
#--- End: if
# Update the m0.ancillary_variable dictionary, because it
# needs to contain the aggregated field.
ancillary_variables[identity] = new_value[0]
new_ancillary_variables.append(new_value[0])
#---End: for
return new_ancillary_variables
#--- End: def
def _share_nc_domain(child, field, role):
'''
perhaps this should be `cf.Field.share_nc_domain`, as it may be useful
in general.
'''
child_axis_to_ncdim = getattr(child.domain, 'nc_dimensions', {})
if len(set(child_axis_to_ncdim.values())) != len(child_axis_to_ncdim):
message = \
"%s %s field can't share domain with its parent field (ambiguous netCDF dimension names)" % \
(role, child.name(''))
return None, message
#--- End: if
field_axis_to_ncdim = getattr(field.domain, 'nc_dimensions', {})
n_axes = len(field_axis_to_ncdim)
field_ncdim_to_axis = dict([(v, k) for k, v in field_axis_to_ncdim.iteritems()])
if len(field_ncdim_to_axis) != n_axes:
message = \
"%s %s field can't share domain with its parent field (ambiguous netCDF dimension names)" % \
(role, child.name(''))
return None, message
#--- End: if
# Remove all items from the childlary field
new_child = child.copy()
new_child.remove_items()
for c_axis in child.data_axes():
# Find the parent field axis (f_axis) which correposnds to the
# child field axis (c_axis)
c_ncdim = child_axis_to_ncdim.get(c_axis, None)
f_axis = field_ncdim_to_axis.get(c_ncdim, None)
if f_axis is None:
message = \
"%s %s field can't share domain with its parent field (axis has no netCDF dimension name)" % \
(role, child.name(''))
return None, message
#--- End: if
# Copy 1-d dimension and auxiliary coordinates from the parent
# field to the child field
for coord in field.coords(axes=f_axis, ndim=1).itervalues():
if coord.isdimension:
new_child.insert_dim(coord, axis=c_axis)
else:
new_child.insert_aux(coord, axes=(c_axis,))
#--- End: for
#--- End: for
return new_child, None
#--- End: def
|