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 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
|
import json
import re
import warnings
from collections import OrderedDict, namedtuple
from pyproj._compat cimport cstrdecode, cstrencode
from pyproj._context cimport _clear_proj_error, pyproj_context_create
from pyproj._context import get_context_manager
from pyproj.aoi import AreaOfUse
from pyproj.crs.datum import CustomEllipsoid
from pyproj.crs.enums import CoordinateOperationType, DatumType
from pyproj.enums import ProjVersion, WktVersion
from pyproj.exceptions import CRSError
from pyproj.geod import pj_ellps
from pyproj.utils import NumpyEncoder
# This is for looking up the ellipsoid parameters
# based on the long name
cdef dict _PJ_ELLPS_NAME_MAP = {
ellps["description"]: ellps_id for ellps_id, ellps in pj_ellps.items()
}
cdef str decode_or_undefined(const char* instring):
pystr = cstrdecode(instring)
if pystr is None:
return "undefined"
return pystr
def is_wkt(str proj_string not None):
"""
.. versionadded:: 2.0.0
Check if the input projection string is in the Well-Known Text format.
Parameters
----------
proj_string: str
The projection string.
Returns
-------
bool: True if the string is in the Well-Known Text format
"""
cdef bytes b_proj_string = cstrencode(proj_string)
return proj_context_guess_wkt_dialect(NULL, b_proj_string) != PJ_GUESSED_NOT_WKT
def is_proj(str proj_string not None):
"""
.. versionadded:: 2.2.2
Check if the input projection string is in the PROJ format.
Parameters
----------
proj_string: str
The projection string.
Returns
-------
bool: True if the string is in the PROJ format
"""
return not is_wkt(proj_string) and "=" in proj_string
cdef _to_wkt(
PJ_CONTEXT* context,
PJ* projobj,
object version,
bint pretty,
bool output_axis_rule=None,
):
"""
Convert a PJ object to a wkt string.
Parameters
----------
context: PJ_CONTEXT*
projobj: PJ*
wkt_out_type: PJ_WKT_TYPE
pretty: bool
output_axis_rule: bool or None
Return
------
str or None
"""
# get the output WKT format
supported_wkt_types = {
WktVersion.WKT2_2015: PJ_WKT2_2015,
WktVersion.WKT2_2015_SIMPLIFIED: PJ_WKT2_2015_SIMPLIFIED,
WktVersion.WKT2_2018: PJ_WKT2_2019,
WktVersion.WKT2_2018_SIMPLIFIED: PJ_WKT2_2019_SIMPLIFIED,
WktVersion.WKT2_2019: PJ_WKT2_2019,
WktVersion.WKT2_2019_SIMPLIFIED: PJ_WKT2_2019_SIMPLIFIED,
WktVersion.WKT1_GDAL: PJ_WKT1_GDAL,
WktVersion.WKT1_ESRI: PJ_WKT1_ESRI
}
cdef PJ_WKT_TYPE wkt_out_type
wkt_out_type = supported_wkt_types[WktVersion.create(version)]
cdef const char* options_wkt[3]
cdef bytes multiline = b"MULTILINE=NO"
if pretty:
multiline = b"MULTILINE=YES"
cdef bytes output_axis = b"OUTPUT_AXIS=AUTO"
if output_axis_rule is False:
output_axis = b"OUTPUT_AXIS=NO"
elif output_axis_rule is True:
output_axis = b"OUTPUT_AXIS=YES"
options_wkt[0] = multiline
options_wkt[1] = output_axis
options_wkt[2] = NULL
cdef const char* proj_string
proj_string = proj_as_wkt(
context,
projobj,
wkt_out_type,
options_wkt,
)
_clear_proj_error()
return cstrdecode(proj_string)
cdef _to_proj4(
PJ_CONTEXT* context,
PJ* projobj,
object version,
bint pretty,
):
"""
Convert the projection to a PROJ string.
Parameters
----------
context: PJ_CONTEXT*
projobj: PJ*
version: pyproj.enums.ProjVersion
The version of the PROJ string output.
pretty: bool
Returns
-------
str: The PROJ string.
"""
# get the output PROJ string format
supported_prj_types = {
ProjVersion.PROJ_4: PJ_PROJ_4,
ProjVersion.PROJ_5: PJ_PROJ_5,
}
cdef PJ_PROJ_STRING_TYPE proj_out_type
proj_out_type = supported_prj_types[ProjVersion.create(version)]
cdef const char* options[2]
cdef bytes multiline = b"MULTILINE=NO"
if pretty:
multiline = b"MULTILINE=YES"
options[0] = multiline
options[1] = NULL
# convert projection to string
cdef const char* proj_string
proj_string = proj_as_proj_string(
context,
projobj,
proj_out_type,
options,
)
_clear_proj_error()
return cstrdecode(proj_string)
cdef tuple _get_concatenated_operations(
PJ_CONTEXT* context, PJ* concatenated_operation
):
"""
For a PJ* of type concatenated operation, get the operations
"""
cdef int step_count = proj_concatoperation_get_step_count(
context,
concatenated_operation,
)
cdef PJ* operation = NULL
cdef PJ_CONTEXT* sub_context = NULL
cdef int iii = 0
operations = []
for iii in range(step_count):
sub_context = pyproj_context_create()
operation = proj_concatoperation_get_step(
sub_context,
concatenated_operation,
iii,
)
operations.append(CoordinateOperation.create(sub_context, operation))
_clear_proj_error()
return tuple(operations)
cdef PJ * _from_name(
PJ_CONTEXT* context,
str name_string,
str auth_name,
PJ_TYPE pj_type,
):
"""
Create an object from a name.
Parameters
----------
context: PJ_CONTEXT*
The context to use to create the object.
name_string: str
Name of object to create.
auth_name: str
The authority name to refine search.
If None, will search all authorities.
pj_type: PJ_TYPE
The type of PJ * to create.
Returns
-------
PJ *
"""
cdef PJ_TYPE[1] pj_types = [pj_type]
cdef char* c_auth_name = NULL
cdef bytes b_auth_name
if auth_name is not None:
b_auth_name = cstrencode(auth_name)
c_auth_name = b_auth_name
cdef PJ_OBJ_LIST *pj_list = proj_create_from_name(
context,
c_auth_name,
cstrencode(name_string),
<PJ_TYPE*>&pj_types,
1,
False,
1,
NULL,
)
if pj_list == NULL or proj_list_get_count(pj_list) <= 0:
proj_list_destroy(pj_list)
return NULL
cdef PJ* datum_pj = proj_list_get(context, pj_list, 0)
proj_list_destroy(pj_list)
return datum_pj
def _load_proj_json(str in_proj_json):
try:
return json.loads(in_proj_json)
except ValueError:
raise CRSError("Invalid JSON")
cdef class Axis:
"""
.. versionadded:: 2.0.0
Coordinate System Axis
Attributes
----------
name: str
abbrev: str
direction: str
unit_conversion_factor: float
unit_name: str
unit_auth_code: str
unit_code: str
"""
def __cinit__(self):
self.name = "undefined"
self.abbrev = "undefined"
self.direction = "undefined"
self.unit_conversion_factor = float("NaN")
self.unit_name = "undefined"
self.unit_auth_code = "undefined"
self.unit_code = "undefined"
def __str__(self):
return f"{self.abbrev}[{self.direction}]: {self.name} ({self.unit_name})"
def __repr__(self):
return (
f"Axis(name={self.name}, abbrev={self.abbrev}, "
f"direction={self.direction}, unit_auth_code={self.unit_auth_code}, "
f"unit_code={self.unit_code}, unit_name={self.unit_name})"
)
@staticmethod
cdef Axis create(PJ_CONTEXT* context, PJ* projobj, int index):
cdef:
Axis axis_info = Axis()
const char * name = NULL
const char * abbrev = NULL
const char * direction = NULL
const char * unit_name = NULL
const char * unit_auth_code = NULL
const char * unit_code = NULL
if not proj_cs_get_axis_info(
context,
projobj,
index,
&name,
&abbrev,
&direction,
&axis_info.unit_conversion_factor,
&unit_name,
&unit_auth_code,
&unit_code):
return None
axis_info.name = decode_or_undefined(name)
axis_info.abbrev = decode_or_undefined(abbrev)
axis_info.direction = decode_or_undefined(direction)
axis_info.unit_name = decode_or_undefined(unit_name)
axis_info.unit_auth_code = decode_or_undefined(unit_auth_code)
axis_info.unit_code = decode_or_undefined(unit_code)
return axis_info
cdef create_area_of_use(PJ_CONTEXT* context, PJ* projobj):
cdef:
double west = float("nan")
double south = float("nan")
double east = float("nan")
double north = float("nan")
const char * area_name = NULL
if not proj_get_area_of_use(
context,
projobj,
&west,
&south,
&east,
&north,
&area_name):
return None
return AreaOfUse(
west=west,
south=south,
east=east,
north=north,
name=decode_or_undefined(area_name),
)
cdef class Base:
def __cinit__(self):
self.projobj = NULL
self.context = NULL
self.name = "undefined"
self._scope = None
self._remarks = None
def __dealloc__(self):
"""destroy projection definition"""
if self.projobj != NULL:
proj_destroy(self.projobj)
cdef _set_base_info(self):
"""
Set the name of the PJ
"""
# get proj information
cdef const char* proj_name = proj_get_name(self.projobj)
self.name = decode_or_undefined(proj_name)
cdef const char* scope = proj_get_scope(self.projobj)
if scope != NULL and scope != "":
self._scope = scope
cdef const char* remarks = proj_get_remarks(self.projobj)
if remarks != NULL and remarks != "":
self._remarks = remarks
@property
def remarks(self):
"""
.. versionadded:: 2.4.0
Returns
-------
str:
Remarks about object.
"""
return self._remarks
@property
def scope(self):
"""
.. versionadded:: 2.4.0
Returns
-------
str:
Scope of object.
"""
return self._scope
def to_wkt(self, version=WktVersion.WKT2_2019, pretty=False, output_axis_rule=None):
"""
Convert the projection to a WKT string.
Version options:
- WKT2_2015
- WKT2_2015_SIMPLIFIED
- WKT2_2019
- WKT2_2019_SIMPLIFIED
- WKT1_GDAL
- WKT1_ESRI
.. versionadded:: 3.6.0 output_axis_rule
Parameters
----------
version: pyproj.enums.WktVersion, default=pyproj.enums.WktVersion.WKT2_2019
The version of the WKT output.
pretty: bool, default=False
If True, it will set the output to be a multiline string.
output_axis_rule: bool, optional, default=None
If True, it will set the axis rule on any case. If false, never.
None for AUTO, that depends on the CRS and version.
Returns
-------
str
"""
return _to_wkt(self.context, self.projobj, version, pretty=pretty, output_axis_rule=output_axis_rule)
def to_json(self, bint pretty=False, int indentation=2):
"""
.. versionadded:: 2.4.0
Convert the object to a JSON string.
Parameters
----------
pretty: bool, default=False
If True, it will set the output to be a multiline string.
indentation: int, default=2
If pretty is True, it will set the width of the indentation.
Returns
-------
str
"""
cdef const char* options[3]
multiline = b"MULTILINE=NO"
if pretty:
multiline = b"MULTILINE=YES"
indentation_width = cstrencode(f"INDENTATION_WIDTH={indentation:.0f}")
options[0] = multiline
options[1] = indentation_width
options[2] = NULL
cdef const char* proj_json_string = proj_as_projjson(
self.context,
self.projobj,
options,
)
return cstrdecode(proj_json_string)
def to_json_dict(self):
"""
.. versionadded:: 2.4.0
Convert the object to a JSON dictionary.
Returns
-------
dict
"""
return json.loads(self.to_json())
def __str__(self):
return self.name
def __repr__(self):
return self.to_wkt(pretty=True)
def _is_exact_same(self, Base other):
return proj_is_equivalent_to_with_ctx(
self.context, self.projobj, other.projobj, PJ_COMP_STRICT) == 1
def _is_equivalent(self, Base other):
return proj_is_equivalent_to_with_ctx(
self.context, self.projobj, other.projobj, PJ_COMP_EQUIVALENT) == 1
def __eq__(self, other):
if not isinstance(other, Base):
return False
return self._is_equivalent(other)
def is_exact_same(self, other):
"""Compares projection objects to see if they are exactly the same."""
if not isinstance(other, Base):
return False
return self._is_exact_same(other)
cdef class _CRSParts(Base):
@classmethod
def from_user_input(cls, user_input):
"""
.. versionadded:: 2.5.0
Create cls from user input:
- PROJ JSON string
- PROJ JSON dict
- WKT string
- An authority string
- An EPSG integer code
- An iterable of ("auth_name", "auth_code")
- An object with a `to_json` method.
Parameters
----------
user_input: str, dict, int, Iterable[str, str]
Input to create cls.
Returns
-------
cls
"""
if isinstance(user_input, str):
prepared = cls.from_string(user_input)
elif isinstance(user_input, dict):
prepared = cls.from_json_dict(user_input)
elif isinstance(user_input, int) and hasattr(cls, "from_epsg"):
prepared = cls.from_epsg(user_input)
elif (
isinstance(user_input, (list, tuple))
and len(user_input) == 2
and hasattr(cls, "from_authority")
):
prepared = cls.from_authority(*user_input)
elif hasattr(user_input, "to_json"):
prepared = cls.from_json(user_input.to_json())
else:
raise CRSError(f"Invalid {cls.__name__} input: {user_input!r}")
return prepared
def __eq__(self, other):
try:
other = self.from_user_input(other)
except CRSError:
return False
return self._is_equivalent(other)
cdef dict _COORD_SYSTEM_TYPE_MAP = {
PJ_CS_TYPE_UNKNOWN: "unknown",
PJ_CS_TYPE_CARTESIAN: "cartesian",
PJ_CS_TYPE_ELLIPSOIDAL: "ellipsoidal",
PJ_CS_TYPE_VERTICAL: "vertical",
PJ_CS_TYPE_SPHERICAL: "spherical",
PJ_CS_TYPE_ORDINAL: "ordinal",
PJ_CS_TYPE_PARAMETRIC: "parametric",
PJ_CS_TYPE_DATETIMETEMPORAL: "datetimetemporal",
PJ_CS_TYPE_TEMPORALCOUNT: "temporalcount",
PJ_CS_TYPE_TEMPORALMEASURE: "temporalmeasure",
}
cdef class CoordinateSystem(_CRSParts):
"""
.. versionadded:: 2.2.0
Coordinate System for CRS
Attributes
----------
name: str
The name of the coordinate system.
"""
def __cinit__(self):
self._axis_list = None
def __init__(self):
raise RuntimeError("CoordinateSystem is not initializable.")
@staticmethod
cdef CoordinateSystem create(PJ_CONTEXT* context, PJ* coord_system_pj):
cdef CoordinateSystem coord_system = CoordinateSystem.__new__(CoordinateSystem)
coord_system.context = context
coord_system._context_manager = get_context_manager()
coord_system.projobj = coord_system_pj
cdef PJ_COORDINATE_SYSTEM_TYPE cs_type = proj_cs_get_type(
coord_system.context,
coord_system.projobj,
)
coord_system.name = _COORD_SYSTEM_TYPE_MAP[cs_type]
return coord_system
@property
def axis_list(self):
"""
Returns
-------
list[Axis]:
The Axis list for the coordinate system.
"""
if self._axis_list is not None:
return self._axis_list
self._axis_list = []
cdef int num_axes = 0
num_axes = proj_cs_get_axis_count(
self.context,
self.projobj
)
for axis_idx from 0 <= axis_idx < num_axes:
self._axis_list.append(
Axis.create(
self.context,
self.projobj,
axis_idx
)
)
return self._axis_list
@staticmethod
def from_string(str coordinate_system_string not None):
"""
.. versionadded:: 2.5.0
.. note:: Only works with PROJ JSON.
Create a Coordinate System from a string.
Parameters
----------
coordinate_system_string: str
Coordinate System string.
Returns
-------
CoordinateSystem
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coordinate_system_pj = proj_create(
context,
cstrencode(coordinate_system_string)
)
if coordinate_system_pj == NULL or proj_cs_get_type(
context,
coordinate_system_pj,
) == PJ_CS_TYPE_UNKNOWN:
proj_destroy(coordinate_system_pj)
raise CRSError(
"Invalid coordinate system string: "
f"{coordinate_system_string}"
)
_clear_proj_error()
return CoordinateSystem.create(context, coordinate_system_pj)
@staticmethod
def from_json_dict(dict coordinate_system_dict not None):
"""
.. versionadded:: 2.5.0
Create Coordinate System from a JSON dictionary.
Parameters
----------
coordinate_system_dict: str
Coordinate System dictionary.
Returns
-------
CoordinateSystem
"""
return CoordinateSystem.from_string(
json.dumps(coordinate_system_dict, cls=NumpyEncoder)
)
@staticmethod
def from_json(str coordinate_system_json_str not None):
"""
.. versionadded:: 2.5.0
Create Coordinate System from a JSON string.
Parameters
----------
coordinate_system_json_str: str
Coordinate System JSON string.
Returns
-------
CoordinateSystem
"""
return CoordinateSystem.from_json_dict(
_load_proj_json(coordinate_system_json_str)
)
def to_cf(self, bint rotated_pole=False):
"""
.. versionadded:: 3.0.0
This converts a :obj:`pyproj.crs.CoordinateSystem` axis
to a list of Climate and Forecast (CF) Version 1.8 dicts.
Parameters
----------
rotated_pole: bool, default=False
If True, the geographic coordinates are on a rotated pole grid.
This corresponds to the rotated_latitude_longitude grid_mapping_name.
Returns
-------
list[dict]:
CF-1.8 version of the CoordinateSystem.
"""
axis_list = self.to_json_dict()["axis"]
cf_params = []
def get_linear_unit(axis):
try:
return f'{axis["unit"]["conversion_factor"]} metre'
except TypeError:
return axis["unit"]
if self.name == "cartesian":
for axis in axis_list:
if axis["name"].lower() == "easting":
cf_axis = "X"
else:
cf_axis = "Y"
cf_params.append(dict(
axis=cf_axis,
long_name=axis["name"],
standard_name=f"projection_{cf_axis.lower()}_coordinate",
units=get_linear_unit(axis),
))
elif self.name == "ellipsoidal":
for axis in axis_list:
if axis["abbreviation"].upper() in ("D", "H"):
cf_params.append(dict(
standard_name="height_above_reference_ellipsoid",
long_name=axis["name"],
units=axis["unit"],
positive=axis["direction"],
axis="Z",
))
else:
if "longitude" in axis["name"].lower():
cf_axis = "X"
name = "longitude"
else:
cf_axis = "Y"
name = "latitude"
if rotated_pole:
cf_params.append(dict(
standard_name=f"grid_{name}",
long_name=f"{name} in rotated pole grid",
units="degrees",
axis=cf_axis,
))
else:
cf_params.append(dict(
standard_name=name,
long_name=f"{name} coordinate",
units=f'degrees_{axis["direction"]}',
axis=cf_axis,
))
elif self.name == "vertical":
for axis in axis_list:
cf_params.append(dict(
standard_name="height_above_reference_ellipsoid",
long_name=axis["name"],
units=get_linear_unit(axis),
positive=axis["direction"],
axis="Z",
))
return cf_params
cdef class Ellipsoid(_CRSParts):
"""
.. versionadded:: 2.0.0
Ellipsoid for CRS
Attributes
----------
name: str
The name of the ellipsoid.
is_semi_minor_computed: int
1 if True, 0 if False
semi_major_metre: float
The semi major axis in meters of the ellipsoid.
semi_minor_metre: float
The semi minor axis in meters of the ellipsoid.
inverse_flattening: float
The inverse flattening of the ellipsoid.
"""
def __cinit__(self):
# load in ellipsoid information if applicable
self.semi_major_metre = float("NaN")
self.semi_minor_metre = float("NaN")
self.is_semi_minor_computed = False
self.inverse_flattening = float("NaN")
def __init__(self):
raise RuntimeError(
"Ellipsoid can only be initialized like 'Ellipsoid.from_*()'."
)
@staticmethod
cdef Ellipsoid create(PJ_CONTEXT* context, PJ* ellipsoid_pj):
cdef Ellipsoid ellips = Ellipsoid.__new__(Ellipsoid)
ellips.context = context
ellips._context_manager = get_context_manager()
ellips.projobj = ellipsoid_pj
cdef int is_semi_minor_computed = 0
proj_ellipsoid_get_parameters(
context,
ellipsoid_pj,
&ellips.semi_major_metre,
&ellips.semi_minor_metre,
&is_semi_minor_computed,
&ellips.inverse_flattening,
)
ellips.is_semi_minor_computed = is_semi_minor_computed == 1
ellips._set_base_info()
_clear_proj_error()
return ellips
@staticmethod
def from_authority(str auth_name not None, code not None):
"""
.. versionadded:: 2.2.0
Create an Ellipsoid from an authority code.
Parameters
----------
auth_name: str
Name of the authority.
code: str or int
The code used by the authority.
Returns
-------
Ellipsoid
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = proj_create_from_database(
context,
cstrencode(auth_name),
cstrencode(str(code)),
PJ_CATEGORY_ELLIPSOID,
False,
NULL,
)
if ellipsoid_pj == NULL:
raise CRSError(f"Invalid authority or code ({auth_name}, {code})")
_clear_proj_error()
return Ellipsoid.create(context, ellipsoid_pj)
@staticmethod
def from_epsg(code not None):
"""
.. versionadded:: 2.2.0
Create an Ellipsoid from an EPSG code.
Parameters
----------
code: str or int
The code used by the EPSG.
Returns
-------
Ellipsoid
"""
return Ellipsoid.from_authority("EPSG", code)
@staticmethod
def _from_string(str ellipsoid_string not None):
"""
Create an Ellipsoid from a string.
Examples:
- urn:ogc:def:ellipsoid:EPSG::7001
- ELLIPSOID["Airy 1830",6377563.396,299.3249646,
LENGTHUNIT["metre",1],
ID["EPSG",7001]]
Parameters
----------
ellipsoid_string: str
Ellipsoid string.
Returns
-------
Ellipsoid
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = proj_create(
context,
cstrencode(ellipsoid_string)
)
if ellipsoid_pj == NULL or proj_get_type(ellipsoid_pj) != PJ_TYPE_ELLIPSOID:
proj_destroy(ellipsoid_pj)
raise CRSError(
f"Invalid ellipsoid string: {ellipsoid_string}"
)
_clear_proj_error()
return Ellipsoid.create(context, ellipsoid_pj)
@staticmethod
def from_string(str ellipsoid_string not None):
"""
.. versionadded:: 2.2.0
Create an Ellipsoid from a string.
Examples:
- urn:ogc:def:ellipsoid:EPSG::7001
- ELLIPSOID["Airy 1830",6377563.396,299.3249646,
LENGTHUNIT["metre",1],
ID["EPSG",7001]]
- WGS 84
Parameters
----------
ellipsoid_string: str
Ellipsoid string.
Returns
-------
Ellipsoid
"""
try:
return Ellipsoid._from_string(ellipsoid_string)
except CRSError as crs_err:
try:
return Ellipsoid.from_name(ellipsoid_string)
except CRSError:
raise crs_err
@staticmethod
def from_json_dict(dict ellipsoid_dict not None):
"""
.. versionadded:: 2.4.0
Create Ellipsoid from a JSON dictionary.
Parameters
----------
ellipsoid_dict: str
Ellipsoid dictionary.
Returns
-------
Ellipsoid
"""
return Ellipsoid._from_string(json.dumps(ellipsoid_dict, cls=NumpyEncoder))
@staticmethod
def from_json(str ellipsoid_json_str not None):
"""
.. versionadded:: 2.4.0
Create Ellipsoid from a JSON string.
Parameters
----------
ellipsoid_json_str: str
Ellipsoid JSON string.
Returns
-------
Ellipsoid
"""
return Ellipsoid.from_json_dict(_load_proj_json(ellipsoid_json_str))
@staticmethod
def _from_name(
str ellipsoid_name,
str auth_name,
):
"""
.. versionadded:: 2.5.0
Create a Ellipsoid from a name.
Parameters
----------
ellipsoid_name: str
Ellipsoid name.
auth_name: str
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
Returns
-------
Ellipsoid
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = _from_name(
context,
ellipsoid_name,
auth_name,
PJ_TYPE_ELLIPSOID,
)
if ellipsoid_pj == NULL:
raise CRSError(f"Invalid ellipsoid name: {ellipsoid_name}")
_clear_proj_error()
return Ellipsoid.create(context, ellipsoid_pj)
@staticmethod
def from_name(
str ellipsoid_name not None,
str auth_name=None,
):
"""
.. versionadded:: 2.5.0
Create a Ellipsoid from a name.
Examples:
- WGS 84
Parameters
----------
ellipsoid_name: str
Ellipsoid name.
auth_name: str, optional
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
Returns
-------
Ellipsoid
"""
try:
return Ellipsoid._from_name(
ellipsoid_name=ellipsoid_name,
auth_name=auth_name,
)
except CRSError:
if auth_name not in ("PROJ", None):
raise
pass
# add support for past names for PROJ ellipsoids
try:
ellipsoid_params = pj_ellps[
_PJ_ELLPS_NAME_MAP.get(ellipsoid_name, ellipsoid_name)
]
except KeyError:
raise CRSError(f"Invalid ellipsoid name: {ellipsoid_name}")
return CustomEllipsoid(
name=ellipsoid_params["description"],
semi_major_axis=ellipsoid_params["a"],
semi_minor_axis=ellipsoid_params.get("b"),
inverse_flattening=ellipsoid_params.get("rf"),
)
cdef class PrimeMeridian(_CRSParts):
"""
.. versionadded:: 2.0.0
Prime Meridian for CRS
Attributes
----------
name: str
The name of the prime meridian.
unit_name: str
The unit name for the prime meridian.
"""
def __cinit__(self):
self.unit_name = None
def __init__(self):
raise RuntimeError(
"PrimeMeridian can only be initialized like 'PrimeMeridian.from_*()'."
)
@staticmethod
cdef PrimeMeridian create(PJ_CONTEXT* context, PJ* prime_meridian_pj):
cdef PrimeMeridian prime_meridian = PrimeMeridian.__new__(PrimeMeridian)
prime_meridian.context = context
prime_meridian._context_manager = get_context_manager()
prime_meridian.projobj = prime_meridian_pj
cdef const char * unit_name
proj_prime_meridian_get_parameters(
prime_meridian.context,
prime_meridian.projobj,
&prime_meridian.longitude,
&prime_meridian.unit_conversion_factor,
&unit_name,
)
prime_meridian.unit_name = decode_or_undefined(unit_name)
prime_meridian._set_base_info()
_clear_proj_error()
return prime_meridian
@staticmethod
def from_authority(str auth_name not None, code not None):
"""
.. versionadded:: 2.2.0
Create a PrimeMeridian from an authority code.
Parameters
----------
auth_name: str
Name of the authority.
code: str or int
The code used by the authority.
Returns
-------
PrimeMeridian
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* prime_meridian_pj = proj_create_from_database(
context,
cstrencode(auth_name),
cstrencode(str(code)),
PJ_CATEGORY_PRIME_MERIDIAN,
False,
NULL,
)
if prime_meridian_pj == NULL:
raise CRSError(f"Invalid authority or code ({auth_name}, {code})")
_clear_proj_error()
return PrimeMeridian.create(context, prime_meridian_pj)
@staticmethod
def from_epsg(code not None):
"""
.. versionadded:: 2.2.0
Create a PrimeMeridian from an EPSG code.
Parameters
----------
code: str or int
The code used by EPSG.
Returns
-------
PrimeMeridian
"""
return PrimeMeridian.from_authority("EPSG", code)
@staticmethod
def _from_string(str prime_meridian_string not None):
"""
Create an PrimeMeridian from a string.
Examples:
- urn:ogc:def:meridian:EPSG::8901
- PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]]
Parameters
----------
prime_meridian_string: str
prime meridian string.
Returns
-------
PrimeMeridian
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* prime_meridian_pj = proj_create(
context,
cstrencode(prime_meridian_string)
)
if (
prime_meridian_pj == NULL or
proj_get_type(prime_meridian_pj) != PJ_TYPE_PRIME_MERIDIAN
):
proj_destroy(prime_meridian_pj)
raise CRSError(
f"Invalid prime meridian string: {prime_meridian_string}"
)
_clear_proj_error()
return PrimeMeridian.create(context, prime_meridian_pj)
@staticmethod
def from_string(str prime_meridian_string not None):
"""
.. versionadded:: 2.2.0
Create an PrimeMeridian from a string.
Examples:
- urn:ogc:def:meridian:EPSG::8901
- PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]]
- Greenwich
Parameters
----------
prime_meridian_string: str
prime meridian string.
Returns
-------
PrimeMeridian
"""
try:
return PrimeMeridian._from_string(prime_meridian_string)
except CRSError as crs_err:
try:
return PrimeMeridian.from_name(prime_meridian_string)
except CRSError:
raise crs_err
@staticmethod
def from_json_dict(dict prime_meridian_dict not None):
"""
.. versionadded:: 2.4.0
Create PrimeMeridian from a JSON dictionary.
Parameters
----------
prime_meridian_dict: str
PrimeMeridian dictionary.
Returns
-------
PrimeMeridian
"""
return PrimeMeridian._from_string(
json.dumps(prime_meridian_dict, cls=NumpyEncoder)
)
@staticmethod
def from_json(str prime_meridian_json_str not None):
"""
.. versionadded:: 2.4.0
Create PrimeMeridian from a JSON string.
Parameters
----------
prime_meridian_json_str: str
PrimeMeridian JSON string.
Returns
-------
PrimeMeridian
"""
return PrimeMeridian.from_json_dict(_load_proj_json(prime_meridian_json_str))
@staticmethod
def from_name(
str prime_meridian_name not None,
str auth_name=None,
):
"""
.. versionadded:: 2.5.0
Create a Prime Meridian from a name.
Examples:
- Greenwich
Parameters
----------
prime_meridian_name: str
Prime Meridian name.
auth_name: str, optional
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
Returns
-------
PrimeMeridian
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* prime_meridian_pj = _from_name(
context,
prime_meridian_name,
auth_name,
PJ_TYPE_PRIME_MERIDIAN,
)
if prime_meridian_pj == NULL:
raise CRSError(
f"Invalid prime meridian name: {prime_meridian_name}"
)
_clear_proj_error()
return PrimeMeridian.create(context, prime_meridian_pj)
cdef dict _DATUM_TYPE_MAP = {
PJ_TYPE_GEODETIC_REFERENCE_FRAME: "Geodetic Reference Frame",
PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME: "Dynamic Geodetic Reference Frame",
PJ_TYPE_VERTICAL_REFERENCE_FRAME: "Vertical Reference Frame",
PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME: "Dynamic Vertical Reference Frame",
PJ_TYPE_DATUM_ENSEMBLE: "Datum Ensemble",
PJ_TYPE_TEMPORAL_DATUM: "Temporal Datum",
PJ_TYPE_ENGINEERING_DATUM: "Engineering Datum",
PJ_TYPE_PARAMETRIC_DATUM: "Parametric Datum",
}
cdef dict _PJ_DATUM_TYPE_MAP = {
DatumType.DATUM_ENSEMBLE: PJ_TYPE_DATUM_ENSEMBLE,
DatumType.GEODETIC_REFERENCE_FRAME: PJ_TYPE_GEODETIC_REFERENCE_FRAME,
DatumType.DYNAMIC_GEODETIC_REFERENCE_FRAME:
PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME,
DatumType.VERTICAL_REFERENCE_FRAME: PJ_TYPE_VERTICAL_REFERENCE_FRAME,
DatumType.DYNAMIC_VERTICAL_REFERENCE_FRAME:
PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME,
}
cdef class Datum(_CRSParts):
"""
.. versionadded:: 2.2.0
Datum for CRS. If it is a compound CRS it is the horizontal datum.
Attributes
----------
name: str
The name of the datum.
"""
def __cinit__(self):
self._ellipsoid = None
self._prime_meridian = None
def __init__(self):
raise RuntimeError(
"Datum can only be initialized like 'Datum.from_*()'."
)
@staticmethod
cdef Datum create(PJ_CONTEXT* context, PJ* datum_pj):
cdef Datum datum = Datum.__new__(Datum)
datum.context = context
datum._context_manager = get_context_manager()
datum.projobj = datum_pj
datum._set_base_info()
datum.type_name = _DATUM_TYPE_MAP[proj_get_type(datum.projobj)]
return datum
@staticmethod
def _from_authority(str auth_name not None, code not None, PJ_CATEGORY category):
"""
Create a Datum from an authority code.
Parameters
----------
auth_name: str
Name of the authority.
code: str or int
The code used by the authority.
Returns
-------
Datum
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* datum_pj = proj_create_from_database(
context,
cstrencode(auth_name),
cstrencode(str(code)),
category,
False,
NULL,
)
if datum_pj == NULL:
raise CRSError(f"Invalid authority or code ({auth_name}, {code})")
_clear_proj_error()
return Datum.create(context, datum_pj)
@staticmethod
def from_authority(str auth_name not None, code not None):
"""
Create a Datum from an authority code.
Parameters
----------
auth_name: str
Name of the authority.
code: str or int
The code used by the authority.
Returns
-------
Datum
"""
try:
return Datum._from_authority(auth_name, code, PJ_CATEGORY_DATUM_ENSEMBLE)
except CRSError:
return Datum._from_authority(auth_name, code, PJ_CATEGORY_DATUM)
@staticmethod
def from_epsg(code not None):
"""
Create a Datum from an EPSG code.
Parameters
----------
code: str or int
The code used by EPSG.
Returns
-------
Datum
"""
return Datum.from_authority("EPSG", code)
@staticmethod
def _from_string(str datum_string not None):
"""
Create a Datum from a string.
Examples:
- urn:ogc:def:datum:EPSG::6326
- DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]],
ID["EPSG",6326]]
Parameters
----------
datum_string: str
Datum string.
Returns
-------
Datum
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* datum_pj = proj_create(
context,
cstrencode(datum_string)
)
if (
datum_pj == NULL or
proj_get_type(datum_pj) not in _DATUM_TYPE_MAP
):
proj_destroy(datum_pj)
raise CRSError(f"Invalid datum string: {datum_string}")
_clear_proj_error()
return Datum.create(context, datum_pj)
@staticmethod
def from_string(str datum_string not None):
"""
Create a Datum from a string.
Examples:
- urn:ogc:def:datum:EPSG::6326
- DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]],
ID["EPSG",6326]]
- World Geodetic System 1984
Parameters
----------
datum_string: str
Datum string.
Returns
-------
Datum
"""
try:
return Datum._from_string(datum_string)
except CRSError as crs_err:
try:
return Datum.from_name(datum_string)
except CRSError:
raise crs_err
@staticmethod
def _from_name(
str datum_name,
str auth_name,
object datum_type,
):
"""
.. versionadded:: 2.5.0
Create a Datum from a name.
Parameters
----------
datum_name: str
Datum name.
auth_name: str
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
datum_type: DatumType
The datum type to create.
Returns
-------
Datum
"""
pj_datum_type = _PJ_DATUM_TYPE_MAP[datum_type]
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* datum_pj = _from_name(
context,
datum_name,
auth_name,
<PJ_TYPE>pj_datum_type,
)
if datum_pj == NULL:
raise CRSError(f"Invalid datum name: {datum_name}")
_clear_proj_error()
return Datum.create(context, datum_pj)
@staticmethod
def from_name(
str datum_name not None,
str auth_name=None,
datum_type=None,
):
"""
.. versionadded:: 2.5.0
Create a Datum from a name.
Examples:
- WGS 84
- World Geodetic System 1984
Parameters
----------
datum_name: str
Datum name.
auth_name: str, optional
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
datum_type: DatumType, optional
The datum type to create. If it is None, it uses any datum type.
Returns
-------
Datum
"""
if datum_type is None:
# try creating name from all datum types
first_error = None
for datum_type in _PJ_DATUM_TYPE_MAP:
try:
return Datum.from_name(
datum_name=datum_name,
auth_name=auth_name,
datum_type=datum_type,
)
except CRSError as err:
if first_error is None:
first_error = err
raise first_error
datum_type = DatumType.create(datum_type)
return Datum._from_name(
datum_name=datum_name,
auth_name=auth_name,
datum_type=datum_type,
)
@staticmethod
def from_json_dict(dict datum_dict not None):
"""
.. versionadded:: 2.4.0
Create Datum from a JSON dictionary.
Parameters
----------
datum_dict: str
Datum dictionary.
Returns
-------
Datum
"""
return Datum._from_string(json.dumps(datum_dict, cls=NumpyEncoder))
@staticmethod
def from_json(str datum_json_str not None):
"""
.. versionadded:: 2.4.0
Create Datum from a JSON string.
Parameters
----------
datum_json_str: str
Datum JSON string.
Returns
-------
Datum
"""
return Datum.from_json_dict(_load_proj_json(datum_json_str))
@property
def ellipsoid(self):
"""
Returns
-------
Ellipsoid:
The ellipsoid object with associated attributes.
"""
if self._ellipsoid is not None:
return None if self._ellipsoid is False else self._ellipsoid
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = proj_get_ellipsoid(
context,
self.projobj,
)
_clear_proj_error()
if ellipsoid_pj == NULL:
self._ellipsoid = False
return None
self._ellipsoid = Ellipsoid.create(context, ellipsoid_pj)
return self._ellipsoid
@property
def prime_meridian(self):
"""
Returns
-------
PrimeMeridian:
The CRS prime meridian object with associated attributes.
"""
if self._prime_meridian is not None:
return None if self._prime_meridian is False else self._prime_meridian
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* prime_meridian_pj = proj_get_prime_meridian(
context,
self.projobj,
)
_clear_proj_error()
if prime_meridian_pj == NULL:
self._prime_meridian = False
return None
self._prime_meridian = PrimeMeridian.create(
context,
prime_meridian_pj,
)
return self._prime_meridian
cdef class Param:
"""
.. versionadded:: 2.2.0
Coordinate operation parameter.
Attributes
----------
name: str
The name of the parameter.
auth_name: str
The authority name of the parameter (i.e. EPSG).
code: str
The code of the parameter (i.e. 9807).
value: str or double
The value of the parameter.
unit_conversion_factor: double
The factor to convert to meters.
unit_name: str
The name of the unit.
unit_auth_name: str
The authority name of the unit (i.e. EPSG).
unit_code: str
The code of the unit (i.e. 9807).
unit_category: str
The category of the unit (“unknown”, “none”, “linear”,
“angular”, “scale”, “time” or “parametric”).
"""
def __cinit__(self):
self.name = "undefined"
self.auth_name = "undefined"
self.code = "undefined"
self.value = "undefined"
self.unit_conversion_factor = float("nan")
self.unit_name = "undefined"
self.unit_auth_name = "undefined"
self.unit_code = "undefined"
self.unit_category = "undefined"
@staticmethod
cdef Param create(PJ_CONTEXT* context, PJ* projobj, int param_idx):
cdef:
Param param = Param()
const char *out_name
const char *out_auth_name
const char *out_code
const char *out_value
const char *out_value_string
const char *out_unit_name
const char *out_unit_auth_name
const char *out_unit_code
const char *out_unit_category
double value_double
proj_coordoperation_get_param(
context,
projobj,
param_idx,
&out_name,
&out_auth_name,
&out_code,
&value_double,
&out_value_string,
¶m.unit_conversion_factor,
&out_unit_name,
&out_unit_auth_name,
&out_unit_code,
&out_unit_category
)
param.name = decode_or_undefined(out_name)
param.auth_name = decode_or_undefined(out_auth_name)
param.code = decode_or_undefined(out_code)
param.unit_name = decode_or_undefined(out_unit_name)
param.unit_auth_name = decode_or_undefined(out_unit_auth_name)
param.unit_code = decode_or_undefined(out_unit_code)
param.unit_category = decode_or_undefined(out_unit_category)
value_string = cstrdecode(out_value_string)
param.value = value_double if value_string is None else value_string
return param
def __str__(self):
return f"{self.auth_name}:{self.auth_code}"
def __repr__(self):
return (
f"Param(name={self.name}, auth_name={self.auth_name}, code={self.code}, "
f"value={self.value}, unit_name={self.unit_name}, "
f"unit_auth_name={self.unit_auth_name}, unit_code={self.unit_code}, "
f"unit_category={self.unit_category})"
)
cdef class Grid:
"""
.. versionadded:: 2.2.0
Coordinate operation grid.
Attributes
----------
short_name: str
The short name of the grid.
full_name: str
The full name of the grid.
package_name: str
The package name where the grid might be found.
url: str
The grid URL or the package URL where the grid might be found.
direct_download: int
If 1, *url* can be downloaded directly.
open_license: int
If 1, the grid is released with an open license.
available: int
If 1, the grid is available at runtime.
"""
def __cinit__(self):
self.short_name = "undefined"
self.full_name = "undefined"
self.package_name = "undefined"
self.url = "undefined"
self.direct_download = False
self.open_license = False
self.available = False
@staticmethod
cdef Grid create(PJ_CONTEXT* context, PJ* projobj, int grid_idx):
cdef:
Grid grid = Grid()
const char *out_short_name
const char *out_full_name
const char *out_package_name
const char *out_url
int direct_download = 0
int open_license = 0
int available = 0
proj_coordoperation_get_grid_used(
context,
projobj,
grid_idx,
&out_short_name,
&out_full_name,
&out_package_name,
&out_url,
&direct_download,
&open_license,
&available
)
grid.short_name = decode_or_undefined(out_short_name)
grid.full_name = decode_or_undefined(out_full_name)
grid.package_name = decode_or_undefined(out_package_name)
grid.url = decode_or_undefined(out_url)
grid.direct_download = direct_download == 1
grid.open_license = open_license == 1
grid.available = available == 1
_clear_proj_error()
return grid
def __str__(self):
return self.full_name
def __repr__(self):
return (
f"Grid(short_name={self.short_name}, full_name={self.full_name}, "
f"package_name={self.package_name}, url={self.url}, "
f"direct_download={self.direct_download}, "
f"open_license={self.open_license}, available={self.available})"
)
cdef dict _COORDINATE_OPERATION_TYPE_MAP = {
PJ_TYPE_UNKNOWN: "Unknown",
PJ_TYPE_CONVERSION: "Conversion",
PJ_TYPE_TRANSFORMATION: "Transformation",
PJ_TYPE_CONCATENATED_OPERATION: "Concatenated Operation",
PJ_TYPE_OTHER_COORDINATE_OPERATION: "Other Coordinate Operation",
}
cdef dict _PJ_COORDINATE_OPERATION_TYPE_MAP = {
CoordinateOperationType.CONVERSION: PJ_TYPE_CONVERSION,
CoordinateOperationType.TRANSFORMATION: PJ_TYPE_TRANSFORMATION,
CoordinateOperationType.CONCATENATED_OPERATION: PJ_TYPE_CONCATENATED_OPERATION,
CoordinateOperationType.OTHER_COORDINATE_OPERATION:
PJ_TYPE_OTHER_COORDINATE_OPERATION,
}
cdef class CoordinateOperation(_CRSParts):
"""
.. versionadded:: 2.2.0
Coordinate operation for CRS.
Attributes
----------
name: str
The name of the method(projection) with authority information.
method_name: str
The method (projection) name.
method_auth_name: str
The method authority name.
method_code: str
The method code.
is_instantiable: int
If 1, a coordinate operation can be instantiated as a PROJ pipeline.
This also checks that referenced grids are available.
has_ballpark_transformation: int
If 1, the coordinate operation has a “ballpark” transformation,
that is a very approximate one, due to lack of more accurate transformations.
accuracy: float
The accuracy (in metre) of a coordinate operation.
"""
def __cinit__(self):
self._params = None
self._grids = None
self._area_of_use = None
self.method_name = "undefined"
self.method_auth_name = "undefined"
self.method_code = "undefined"
self.is_instantiable = False
self.has_ballpark_transformation = False
self.accuracy = float("nan")
self._towgs84 = None
self._operations = None
def __init__(self):
raise RuntimeError(
"CoordinateOperation can only be initialized like "
"CoordinateOperation.from_*()'."
)
@staticmethod
cdef CoordinateOperation create(PJ_CONTEXT* context, PJ* coord_operation_pj):
cdef CoordinateOperation coord_operation = CoordinateOperation.__new__(
CoordinateOperation
)
coord_operation.context = context
coord_operation._context_manager = get_context_manager()
coord_operation.projobj = coord_operation_pj
cdef const char *out_method_name = NULL
cdef const char *out_method_auth_name = NULL
cdef const char *out_method_code = NULL
proj_coordoperation_get_method_info(
coord_operation.context,
coord_operation.projobj,
&out_method_name,
&out_method_auth_name,
&out_method_code
)
coord_operation._set_base_info()
coord_operation.method_name = decode_or_undefined(out_method_name)
coord_operation.method_auth_name = decode_or_undefined(out_method_auth_name)
coord_operation.method_code = decode_or_undefined(out_method_code)
coord_operation.accuracy = proj_coordoperation_get_accuracy(
coord_operation.context,
coord_operation.projobj
)
coord_operation.is_instantiable = proj_coordoperation_is_instantiable(
coord_operation.context,
coord_operation.projobj
) == 1
coord_operation.has_ballpark_transformation = \
proj_coordoperation_has_ballpark_transformation(
coord_operation.context,
coord_operation.projobj
) == 1
cdef PJ_TYPE operation_type = proj_get_type(coord_operation.projobj)
coord_operation.type_name = _COORDINATE_OPERATION_TYPE_MAP[operation_type]
_clear_proj_error()
return coord_operation
@staticmethod
def from_authority(
str auth_name not None,
code not None,
bint use_proj_alternative_grid_names=False,
):
"""
Create a CoordinateOperation from an authority code.
Parameters
----------
auth_name: str
Name of the authority.
code: str or int
The code used by the authority.
use_proj_alternative_grid_names: bool, default=False
Use the PROJ alternative grid names.
Returns
-------
CoordinateOperation
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coord_operation_pj = proj_create_from_database(
context,
cstrencode(auth_name),
cstrencode(str(code)),
PJ_CATEGORY_COORDINATE_OPERATION,
use_proj_alternative_grid_names,
NULL,
)
if coord_operation_pj == NULL:
raise CRSError(f"Invalid authority or code ({auth_name}, {code})")
_clear_proj_error()
return CoordinateOperation.create(context, coord_operation_pj)
@staticmethod
def from_epsg(code not None, bint use_proj_alternative_grid_names= False):
"""
Create a CoordinateOperation from an EPSG code.
Parameters
----------
code: str or int
The code used by EPSG.
use_proj_alternative_grid_names: bool, default=False
Use the PROJ alternative grid names.
Returns
-------
CoordinateOperation
"""
return CoordinateOperation.from_authority(
"EPSG", code, use_proj_alternative_grid_names
)
@staticmethod
def _from_string(str coordinate_operation_string not None):
"""
Create a CoordinateOperation from a string.
Example:
- urn:ogc:def:coordinateOperation:EPSG::1671
Parameters
----------
coordinate_operation_string: str
Coordinate operation string.
Returns
-------
CoordinateOperation
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coord_operation_pj = proj_create(
context,
cstrencode(coordinate_operation_string)
)
if (
coord_operation_pj == NULL or
proj_get_type(coord_operation_pj) not in (
PJ_TYPE_CONVERSION,
PJ_TYPE_TRANSFORMATION,
PJ_TYPE_CONCATENATED_OPERATION,
PJ_TYPE_OTHER_COORDINATE_OPERATION,
)
):
proj_destroy(coord_operation_pj)
raise CRSError(
"Invalid coordinate operation string: "
f"{coordinate_operation_string}"
)
_clear_proj_error()
return CoordinateOperation.create(context, coord_operation_pj)
@staticmethod
def from_string(str coordinate_operation_string not None):
"""
Create a CoordinateOperation from a string.
Example:
- urn:ogc:def:coordinateOperation:EPSG::1671
- UTM zone 14N
- +proj=utm +zone=14
Parameters
----------
coordinate_operation_string: str
Coordinate operation string.
Returns
-------
CoordinateOperation
"""
try:
return CoordinateOperation._from_string(coordinate_operation_string)
except CRSError as crs_err:
try:
return CoordinateOperation.from_name(coordinate_operation_string)
except CRSError:
raise crs_err
@staticmethod
def from_json_dict(dict coordinate_operation_dict not None):
"""
Create CoordinateOperation from a JSON dictionary.
.. versionadded:: 2.4.0
Parameters
----------
coordinate_operation_dict: str
CoordinateOperation dictionary.
Returns
-------
CoordinateOperation
"""
return CoordinateOperation._from_string(
json.dumps(coordinate_operation_dict, cls=NumpyEncoder)
)
@staticmethod
def from_json(str coordinate_operation_json_str not None):
"""
Create CoordinateOperation from a JSON string.
.. versionadded:: 2.4.0
Parameters
----------
coordinate_operation_json_str: str
CoordinateOperation JSON string.
Returns
-------
CoordinateOperation
"""
return CoordinateOperation.from_json_dict(
_load_proj_json(coordinate_operation_json_str
))
@staticmethod
def from_name(
str coordinate_operation_name not None,
str auth_name=None,
coordinate_operation_type not None=CoordinateOperationType.CONVERSION,
):
"""
.. versionadded:: 2.5.0
Create a Coordinate Operation from a name.
Examples:
- UTM zone 14N
Parameters
----------
coordinate_operation_name: str
Coordinate Operation name.
auth_name: str, optional
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
coordinate_operation_type: CoordinateOperationType, optional
The coordinate operation type to create. Default is
``pyproj.crs.enums.CoordinateOperationType.CONVERSION``
Returns
-------
CoordinateOperation
"""
pj_coordinate_operation_type = _PJ_COORDINATE_OPERATION_TYPE_MAP[
CoordinateOperationType.create(coordinate_operation_type)
]
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coordinate_operation_pj = _from_name(
context,
coordinate_operation_name,
auth_name,
<PJ_TYPE>pj_coordinate_operation_type,
)
if coordinate_operation_pj == NULL:
raise CRSError(
"Invalid coordinate operation name: "
f"{coordinate_operation_name}"
)
_clear_proj_error()
return CoordinateOperation.create(context, coordinate_operation_pj)
@property
def params(self):
"""
Returns
-------
list[Param]:
The coordinate operation parameters.
"""
if self._params is not None:
return self._params
self._params = []
cdef int num_params = 0
num_params = proj_coordoperation_get_param_count(
self.context,
self.projobj
)
for param_idx from 0 <= param_idx < num_params:
self._params.append(
Param.create(
self.context,
self.projobj,
param_idx
)
)
_clear_proj_error()
return self._params
@property
def grids(self):
"""
Returns
-------
list[Grid]:
The coordinate operation grids.
"""
if self._grids is not None:
return self._grids
self._grids = []
cdef int num_grids = 0
num_grids = proj_coordoperation_get_grid_used_count(
self.context,
self.projobj
)
for grid_idx from 0 <= grid_idx < num_grids:
self._grids.append(
Grid.create(
self.context,
self.projobj,
grid_idx
)
)
_clear_proj_error()
return self._grids
@property
def area_of_use(self):
"""
Returns
-------
AreaOfUse:
The area of use object with associated attributes.
"""
if self._area_of_use is not None:
return self._area_of_use
self._area_of_use = create_area_of_use(self.context, self.projobj)
return self._area_of_use
def to_proj4(self, version not None=ProjVersion.PROJ_5, bint pretty=False):
"""
Convert the projection to a PROJ string.
.. versionadded:: 3.1.0 pretty
Parameters
----------
version: pyproj.enums.ProjVersion, default=pyproj.enums.ProjVersion.PROJ_5
The version of the PROJ string output.
pretty: bool, default=False
If True, it will set the output to be a multiline string.
Returns
-------
str:
The PROJ string.
"""
return _to_proj4(self.context, self.projobj, version=version, pretty=pretty)
@property
def towgs84(self):
"""
Returns
-------
list[float]:
A list of 3 or 7 towgs84 values if they exist.
"""
if self._towgs84 is not None:
return self._towgs84
towgs84_dict = OrderedDict(
(
('X-axis translation', None),
('Y-axis translation', None),
('Z-axis translation', None),
('X-axis rotation', None),
('Y-axis rotation', None),
('Z-axis rotation', None),
('Scale difference', None),
)
)
for param in self.params:
if param.name in towgs84_dict:
towgs84_dict[param.name] = param.value
self._towgs84 = [val for val in towgs84_dict.values() if val is not None]
return self._towgs84
@property
def operations(self):
"""
.. versionadded:: 2.4.0
Returns
-------
tuple[CoordinateOperation]:
The operations in a concatenated operation.
"""
if self._operations is not None:
return self._operations
self._operations = _get_concatenated_operations(self.context, self.projobj)
return self._operations
def __repr__(self):
return (
f"<Coordinate Operation: {self.type_name}>\n"
f"Name: {self.name}\n"
f"Method: {self.method_name}\n"
f"Area of Use:\n{self.area_of_use or '- undefined'}"
)
AuthorityMatchInfo = namedtuple(
"AuthorityMatchInfo",
[
"auth_name",
"code",
"confidence",
],
)
AuthorityMatchInfo.__doc__ = """
.. versionadded:: 3.2.0
CRS Authority Match Information
Parameters
----------
auth_name: str
Authority name.
code: str
Object code.
confidence: int
Confidence that this CRS matches
the authority and code.
"""
cdef dict _CRS_TYPE_MAP = {
PJ_TYPE_UNKNOWN: "Unknown CRS",
PJ_TYPE_CRS: "CRS",
PJ_TYPE_GEODETIC_CRS: "Geodetic CRS",
PJ_TYPE_GEOCENTRIC_CRS: "Geocentric CRS",
PJ_TYPE_GEOGRAPHIC_CRS: "Geographic CRS",
PJ_TYPE_GEOGRAPHIC_2D_CRS: "Geographic 2D CRS",
PJ_TYPE_GEOGRAPHIC_3D_CRS: "Geographic 3D CRS",
PJ_TYPE_VERTICAL_CRS: "Vertical CRS",
PJ_TYPE_PROJECTED_CRS: "Projected CRS",
PJ_TYPE_COMPOUND_CRS: "Compound CRS",
PJ_TYPE_TEMPORAL_CRS: "Temporal CRS",
PJ_TYPE_ENGINEERING_CRS: "Engineering CRS",
PJ_TYPE_BOUND_CRS: "Bound CRS",
PJ_TYPE_OTHER_CRS: "Other CRS",
PJ_TYPE_DERIVED_PROJECTED_CRS: "Derived Projected CRS",
}
cdef class _CRS(Base):
"""
.. versionadded:: 2.0.0
The cython CRS class to be used as the base for the
python CRS class.
"""
def __cinit__(self):
self._context_manager = None
self._ellipsoid = None
self._area_of_use = None
self._prime_meridian = None
self._datum = None
self._sub_crs_list = None
self._source_crs = None
self._target_crs = None
self._geodetic_crs = None
self._coordinate_system = None
self._coordinate_operation = None
self._type_name = None
def __init__(self, str proj_string):
self.context = pyproj_context_create()
self._context_manager = get_context_manager()
# initialize projection
self.projobj = proj_create(
self.context,
cstrencode(proj_string),
)
if self.projobj == NULL:
raise CRSError(f"Invalid projection: {proj_string}")
# make sure the input is a CRS
if not proj_is_crs(self.projobj):
raise CRSError(f"Input is not a CRS: {proj_string}")
# set proj information
self.srs = proj_string
self._type = proj_get_type(self.projobj)
self._set_base_info()
_clear_proj_error()
@property
def type_name(self):
"""
Returns
-------
str:
The name of the type of the CRS object.
"""
if self._type_name is not None:
return self._type_name
self._type_name = _CRS_TYPE_MAP[self._type]
if not self.is_derived or self._type in (
PJ_TYPE_PROJECTED_CRS,
PJ_TYPE_DERIVED_PROJECTED_CRS,
):
# Projected CRS are derived by definition
# https://github.com/OSGeo/PROJ/issues/3525#issuecomment-1365790999
return self._type_name
self._type_name = f"Derived {self._type_name}"
return self._type_name
@property
def axis_info(self):
"""
Retrieves all relevant axis information in the CRS.
If it is a Bound CRS, it gets the axis list from the Source CRS.
If it is a Compound CRS, it gets the axis list from the Sub CRS list.
Returns
-------
list[Axis]:
The list of axis information.
"""
axis_info_list = []
if self.coordinate_system:
axis_info_list.extend(self.coordinate_system.axis_list)
elif self.is_bound and self.source_crs:
axis_info_list.extend(self.source_crs.axis_info)
else:
for sub_crs in self.sub_crs_list:
axis_info_list.extend(sub_crs.axis_info)
return axis_info_list
@property
def area_of_use(self):
"""
Returns
-------
AreaOfUse:
The area of use object with associated attributes.
"""
if self._area_of_use is not None:
return self._area_of_use
self._area_of_use = create_area_of_use(self.context, self.projobj)
return self._area_of_use
@property
def ellipsoid(self):
"""
.. versionadded:: 2.2.0
Returns
-------
Ellipsoid:
The ellipsoid object with associated attributes.
"""
if self._ellipsoid is not None:
return None if self._ellipsoid is False else self._ellipsoid
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = proj_get_ellipsoid(
context,
self.projobj
)
_clear_proj_error()
if ellipsoid_pj == NULL:
self._ellipsoid = False
return None
self._ellipsoid = Ellipsoid.create(context, ellipsoid_pj)
return self._ellipsoid
@property
def prime_meridian(self):
"""
.. versionadded:: 2.2.0
Returns
-------
PrimeMeridian:
The prime meridian object with associated attributes.
"""
if self._prime_meridian is not None:
return None if self._prime_meridian is True else self._prime_meridian
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* prime_meridian_pj = proj_get_prime_meridian(
context,
self.projobj,
)
_clear_proj_error()
if prime_meridian_pj == NULL:
self._prime_meridian = False
return None
self._prime_meridian = PrimeMeridian.create(context, prime_meridian_pj)
return self._prime_meridian
@property
def datum(self):
"""
.. versionadded:: 2.2.0
Returns
-------
Datum
"""
if self._datum is not None:
return None if self._datum is False else self._datum
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* datum_pj = proj_crs_get_datum(
context,
self.projobj,
)
if datum_pj == NULL:
datum_pj = proj_crs_get_horizontal_datum(
context,
self.projobj,
)
_clear_proj_error()
if datum_pj == NULL:
self._datum = False
return None
self._datum = Datum.create(context, datum_pj)
return self._datum
@property
def coordinate_system(self):
"""
.. versionadded:: 2.2.0
Returns
-------
CoordinateSystem
"""
if self._coordinate_system is not None:
return None if self._coordinate_system is False else self._coordinate_system
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coord_system_pj = proj_crs_get_coordinate_system(
context,
self.projobj
)
_clear_proj_error()
if coord_system_pj == NULL:
self._coordinate_system = False
return None
self._coordinate_system = CoordinateSystem.create(
context,
coord_system_pj,
)
return self._coordinate_system
@property
def coordinate_operation(self):
"""
.. versionadded:: 2.2.0
Returns
-------
CoordinateOperation
"""
if self._coordinate_operation is not None:
return (
None
if self._coordinate_operation is False
else self._coordinate_operation
)
if not (
self.is_bound or self.is_derived
):
self._coordinate_operation = False
return None
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coord_pj = proj_crs_get_coordoperation(
context,
self.projobj
)
_clear_proj_error()
if coord_pj == NULL:
self._coordinate_operation = False
return None
self._coordinate_operation = CoordinateOperation.create(
context,
coord_pj,
)
return self._coordinate_operation
@property
def source_crs(self):
"""
Returns
-------
_CRS:
The base CRS of a BoundCRS or a DerivedCRS/ProjectedCRS.
"""
if self._source_crs is not None:
return None if self._source_crs is False else self._source_crs
cdef PJ * projobj = proj_get_source_crs(self.context, self.projobj)
_clear_proj_error()
if projobj == NULL:
self._source_crs = False
return None
try:
self._source_crs = _CRS(_to_wkt(
self.context,
projobj,
version=WktVersion.WKT2_2019,
pretty=False,
))
finally:
proj_destroy(projobj)
return self._source_crs
@property
def target_crs(self):
"""
.. versionadded:: 2.2.0
Returns
-------
_CRS:
The hub CRS of a BoundCRS.
"""
if self._target_crs is not None:
return None if self._target_crs is False else self._target_crs
cdef PJ * projobj = proj_get_target_crs(self.context, self.projobj)
_clear_proj_error()
if projobj == NULL:
self._target_crs = False
return None
try:
self._target_crs = _CRS(_to_wkt(
self.context,
projobj,
version=WktVersion.WKT2_2019,
pretty=False,
))
finally:
proj_destroy(projobj)
return self._target_crs
@property
def sub_crs_list(self):
"""
If the CRS is a compound CRS, it will return a list of sub CRS objects.
Returns
-------
list[_CRS]
"""
if self._sub_crs_list is not None:
return self._sub_crs_list
if not self.is_compound:
self._sub_crs_list = []
return self._sub_crs_list
cdef int iii = 0
cdef PJ * projobj = proj_crs_get_sub_crs(
self.context,
self.projobj,
iii,
)
self._sub_crs_list = []
while projobj != NULL:
try:
self._sub_crs_list.append(_CRS(_to_wkt(
self.context,
projobj,
version=WktVersion.WKT2_2019,
pretty=False,
)))
finally:
proj_destroy(projobj) # deallocate temp proj
iii += 1
projobj = proj_crs_get_sub_crs(
self.context,
self.projobj,
iii,
)
_clear_proj_error()
return self._sub_crs_list
@property
def geodetic_crs(self):
"""
.. versionadded:: 2.2.0
The geodeticCRS / geographicCRS from the CRS.
Returns
-------
_CRS
"""
if self._geodetic_crs is not None:
return self._geodetic_crs if self. _geodetic_crs is not False else None
cdef PJ * projobj = proj_crs_get_geodetic_crs(self.context, self.projobj)
_clear_proj_error()
if projobj == NULL:
self._geodetic_crs = False
return None
try:
self._geodetic_crs = _CRS(_to_wkt(
self.context,
projobj,
version=WktVersion.WKT2_2019,
pretty=False,
))
finally:
proj_destroy(projobj) # deallocate temp proj
return self._geodetic_crs
def to_proj4(self, version=ProjVersion.PROJ_4):
"""
Convert the projection to a PROJ string.
.. warning:: You will likely lose important projection
information when converting to a PROJ string from
another format. See:
https://proj.org/faq.html#what-is-the-best-format-for-describing-coordinate-reference-systems # noqa: E501
Parameters
----------
version: pyproj.enums.ProjVersion, default=pyproj.enums.ProjVersion.PROJ_4
The version of the PROJ string output.
Returns
-------
str
"""
warnings.warn(
"You will likely lose important projection information when "
"converting to a PROJ string from another format. See: "
"https://proj.org/faq.html#what-is-the-best-format-for-describing-"
"coordinate-reference-systems"
)
return _to_proj4(self.context, self.projobj, version=version, pretty=False)
def to_epsg(self, int min_confidence=70):
"""
Return the EPSG code best matching the CRS
or None if it a match is not found.
Example:
>>> from pyproj import CRS
>>> ccs = CRS("EPSG:4328")
>>> ccs.to_epsg()
4328
If the CRS is bound, you can attempt to get an epsg code from
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.to_epsg()
>>> ccs.source_crs.to_epsg()
4978
>>> ccs == CRS.from_epsg(4978)
False
Parameters
----------
min_confidence: int, default=70
A value between 0-100 where 100 is the most confident.
:ref:`min_confidence`
Returns
-------
int | None:
The best matching EPSG code matching the confidence level.
"""
auth_info = self.to_authority(
auth_name="EPSG",
min_confidence=min_confidence
)
if auth_info is not None and auth_info[0].upper() == "EPSG":
return int(auth_info[1])
return None
def to_authority(self, str auth_name=None, int min_confidence=70):
"""
.. versionadded:: 2.2.0
Return the authority name and code best matching the CRS
or None if it a match is not found.
Example:
>>> from pyproj import CRS
>>> ccs = CRS("EPSG:4328")
>>> ccs.to_authority()
('EPSG', '4328')
If the CRS is bound, you can get an authority from
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.to_authority()
>>> ccs.source_crs.to_authority()
('EPSG', '4978')
>>> ccs == CRS.from_authorty('EPSG', '4978')
False
Parameters
----------
auth_name: str, optional
The name of the authority to filter by.
min_confidence: int, default=70
A value between 0-100 where 100 is the most confident.
:ref:`min_confidence`
Returns
-------
tuple(str, str) or None:
The best matching (<auth_name>, <code>) for the confidence level.
"""
try:
authority = self.list_authority(
auth_name=auth_name, min_confidence=min_confidence,
)[0]
return authority.auth_name, authority.code
except IndexError:
return None
def list_authority(self, str auth_name=None, int min_confidence=70):
"""
.. versionadded:: 3.2.0
Return the authority names and codes best matching the CRS.
Example:
>>> from pyproj import CRS
>>> ccs = CRS("EPSG:4328")
>>> ccs.list_authority()
[AuthorityMatchInfo(auth_name='EPSG', code='4326', confidence=100)]
If the CRS is bound, you can get an authority from
the source CRS:
>>> from pyproj import CRS
>>> ccs = CRS("+proj=geocent +datum=WGS84 +towgs84=0,0,0")
>>> ccs.list_authority()
[]
>>> ccs.source_crs.list_authority()
[AuthorityMatchInfo(auth_name='EPSG', code='4978', confidence=70)]
>>> ccs == CRS.from_authorty('EPSG', '4978')
False
Parameters
----------
auth_name: str, optional
The name of the authority to filter by.
min_confidence: int, default=70
A value between 0-100 where 100 is the most confident.
:ref:`min_confidence`
Returns
-------
list[AuthorityMatchInfo]:
List of authority matches for the CRS.
"""
# get list of possible matching projections
cdef PJ_OBJ_LIST *proj_list = NULL
cdef int *c_out_confidence_list = NULL
cdef int num_proj_objects = -9999
cdef bytes b_auth_name
cdef char *user_auth_name = NULL
cdef int iii = 0
if auth_name is not None:
b_auth_name = cstrencode(auth_name)
user_auth_name = b_auth_name
out_confidence_list = []
try:
proj_list = proj_identify(
self.context,
self.projobj,
user_auth_name,
NULL,
&c_out_confidence_list
)
if proj_list != NULL:
num_proj_objects = proj_list_get_count(proj_list)
if c_out_confidence_list != NULL and num_proj_objects > 0:
out_confidence_list = [
c_out_confidence_list[iii] for iii in range(num_proj_objects)
]
finally:
if c_out_confidence_list != NULL:
proj_int_list_destroy(c_out_confidence_list)
_clear_proj_error()
# retrieve the best matching projection
cdef PJ* proj = NULL
cdef const char* code
cdef const char* out_auth_name
authority_list = []
try:
for iii in range(num_proj_objects):
if out_confidence_list[iii] < min_confidence:
continue
proj = proj_list_get(self.context, proj_list, iii)
code = proj_get_id_code(proj, 0)
out_auth_name = proj_get_id_auth_name(proj, 0)
if out_auth_name != NULL and code != NULL:
authority_list.append(
AuthorityMatchInfo(
out_auth_name,
code,
out_confidence_list[iii]
)
)
# at this point, the auth name is copied and we can release the proj object
proj_destroy(proj)
proj = NULL
finally:
# If there was an error we have to call proj_destroy
# If there was none, calling it on NULL does nothing
proj_destroy(proj)
proj_list_destroy(proj_list)
_clear_proj_error()
return authority_list
def to_3d(self, str name=None):
"""
.. versionadded:: 3.1.0
Convert the current CRS to the 3D version if it makes sense.
New vertical axis attributes:
- ellipsoidal height
- oriented upwards
- metre units
Parameters
----------
name: str, optional
CRS name. If None, it will use the name of the original CRS.
Returns
-------
_CRS
"""
cdef char* c_name = NULL
cdef bytes b_name
if name is not None:
b_name = cstrencode(name)
c_name = b_name
cdef PJ * projobj = proj_crs_promote_to_3D(
self.context, c_name, self.projobj
)
_clear_proj_error()
if projobj == NULL:
return self
try:
crs_3d = _CRS(_to_wkt(
self.context,
projobj,
version=WktVersion.WKT2_2019,
pretty=False,
))
finally:
proj_destroy(projobj)
return crs_3d
def to_2d(self, str name=None):
"""
.. versionadded:: 3.6.0
Convert the current CRS to the 2D version if it makes sense.
Parameters
----------
name: str, optional
CRS name. If None, it will use the name of the original CRS.
Returns
-------
_CRS
"""
cdef char* c_name = NULL
cdef bytes b_name
if name is not None:
b_name = cstrencode(name)
c_name = b_name
cdef PJ * projobj = proj_crs_demote_to_2D(
self.context, c_name, self.projobj
)
_clear_proj_error()
if projobj == NULL:
return self
try:
crs_2d = _CRS(_to_wkt(
self.context,
projobj,
version=WktVersion.WKT2_2019,
pretty=False,
))
finally:
proj_destroy(projobj)
return crs_2d
def _is_crs_property(
self, str property_name, tuple property_types, int sub_crs_index=0
):
"""
.. versionadded:: 2.2.0
This method will check for a property on the CRS.
It will check if it has the property on the sub CRS
if it is a compound CRS and will check if the source CRS
has the property if it is a bound CRS.
Parameters
----------
property_name: str
The name of the CRS property.
property_types: tuple(PJ_TYPE)
The types to check for for the property.
sub_crs_index: int, default=0
THe index of the CRS in the sub CRS list.
Returns
-------
bool:
True if the CRS has this property.
"""
if self.sub_crs_list:
sub_crs = self.sub_crs_list[sub_crs_index]
if sub_crs.is_bound:
is_property = getattr(sub_crs.source_crs, property_name)
else:
is_property = getattr(sub_crs, property_name)
elif self.is_bound:
is_property = getattr(self.source_crs, property_name)
else:
is_property = self._type in property_types
return is_property
@property
def is_geographic(self):
"""
This checks if the CRS is geographic.
It will check if it has a geographic CRS
in the sub CRS if it is a compound CRS and will check if
the source CRS is geographic if it is a bound CRS.
Returns
-------
bool:
True if the CRS is in geographic (lon/lat) coordinates.
"""
return self._is_crs_property(
"is_geographic",
(
PJ_TYPE_GEOGRAPHIC_CRS,
PJ_TYPE_GEOGRAPHIC_2D_CRS,
PJ_TYPE_GEOGRAPHIC_3D_CRS
)
)
@property
def is_projected(self):
"""
This checks if the CRS is projected.
It will check if it has a projected CRS
in the sub CRS if it is a compound CRS and will check if
the source CRS is projected if it is a bound CRS.
Returns
-------
bool:
True if CRS is projected.
"""
return self._is_crs_property(
"is_projected",
(PJ_TYPE_PROJECTED_CRS,)
)
@property
def is_vertical(self):
"""
.. versionadded:: 2.2.0
This checks if the CRS is vertical.
It will check if it has a vertical CRS
in the sub CRS if it is a compound CRS and will check if
the source CRS is vertical if it is a bound CRS.
Returns
-------
bool:
True if CRS is vertical.
"""
return self._is_crs_property(
"is_vertical",
(PJ_TYPE_VERTICAL_CRS,),
sub_crs_index=1
)
@property
def is_bound(self):
"""
Returns
-------
bool:
True if CRS is bound.
"""
return self._type == PJ_TYPE_BOUND_CRS
@property
def is_compound(self):
"""
.. versionadded:: 3.1.0
Returns
-------
bool:
True if CRS is compound.
"""
return self._type == PJ_TYPE_COMPOUND_CRS
@property
def is_engineering(self):
"""
.. versionadded:: 2.2.0
Returns
-------
bool:
True if CRS is local/engineering.
"""
return self._type == PJ_TYPE_ENGINEERING_CRS
@property
def is_geocentric(self):
"""
This checks if the CRS is geocentric and
takes into account if the CRS is bound.
Returns
-------
bool:
True if CRS is in geocentric (x/y) coordinates.
"""
if self.is_bound:
return self.source_crs.is_geocentric
return self._type == PJ_TYPE_GEOCENTRIC_CRS
@property
def is_derived(self):
"""
.. versionadded:: 3.2.0
Returns
-------
bool:
True if CRS is a Derived CRS.
"""
return proj_is_derived_crs(self.context, self.projobj) == 1
def _equals(self, _CRS other, bint ignore_axis_order):
if ignore_axis_order:
# Only to be used with DerivedCRS/ProjectedCRS/GeographicCRS
return proj_is_equivalent_to_with_ctx(
self.context,
self.projobj,
other.projobj,
PJ_COMP_EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS,
) == 1
return self._is_equivalent(other)
def equals(self, other, ignore_axis_order=False):
"""
Check if the projection objects are equivalent.
Properties
----------
other: CRS
Check if the other object
ignore_axis_order: bool, default=False
If True, it will compare the CRS class and ignore the axis order.
Returns
-------
bool
"""
if not isinstance(other, _CRS):
return False
return self._equals(other, ignore_axis_order=ignore_axis_order)
@property
def is_deprecated(self):
"""
.. versionadded:: 3.7.0
Check if the CRS is deprecated
Returns
-------
bool
"""
return bool(proj_is_deprecated(self.projobj))
def get_non_deprecated(self):
"""
.. versionadded:: 3.7.0
Return a list of non-deprecated objects related to this.
Returns
-------
list[_CRS]
"""
non_deprecated = []
cdef PJ_OBJ_LIST *proj_list = NULL
cdef int num_proj_objects = 0
proj_list = proj_get_non_deprecated(
self.context,
self.projobj
)
if proj_list != NULL:
num_proj_objects = proj_list_get_count(proj_list)
cdef PJ* proj = NULL
try:
for iii in range(num_proj_objects):
proj = proj_list_get(self.context, proj_list, iii)
non_deprecated.append(_CRS(_to_wkt(
self.context,
proj,
version=WktVersion.WKT2_2019,
pretty=False,
)))
proj_destroy(proj)
proj = NULL
finally:
# If there was an error we have to call proj_destroy
# If there was none, calling it on NULL does nothing
proj_destroy(proj)
proj_list_destroy(proj_list)
_clear_proj_error()
return non_deprecated
|