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 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195
|
"""PyVista plotting module."""
from __future__ import annotations
from collections.abc import Iterable
import contextlib
from contextlib import contextmanager
from contextlib import suppress
from copy import deepcopy
import ctypes
from functools import wraps
import io
import logging
import os
from pathlib import Path
import platform
import sys
import textwrap
from threading import Thread
import time
from typing import TYPE_CHECKING
import uuid
import warnings
import weakref
import matplotlib as mpl
import numpy as np
import scooby
import pyvista
from pyvista.core.errors import MissingDataError
from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.arrays import FieldAssociation
from pyvista.core.utilities.arrays import _coerce_pointslike_arg
from pyvista.core.utilities.arrays import convert_array
from pyvista.core.utilities.arrays import get_array
from pyvista.core.utilities.arrays import get_array_association
from pyvista.core.utilities.arrays import raise_not_matching
from pyvista.core.utilities.helpers import is_pyvista_dataset
from pyvista.core.utilities.helpers import wrap
from pyvista.core.utilities.misc import abstract_class
from pyvista.core.utilities.misc import assert_empty_kwargs
from . import _vtk
from ._plotting import _common_arg_parser
from ._plotting import prepare_smooth_shading
from ._plotting import process_opacity
from ._property import Property
from .actor import Actor
from .colors import Color
from .colors import get_cmap_safe
from .composite_mapper import CompositePolyDataMapper
from .errors import RenderWindowUnavailable
from .mapper import DataSetMapper
from .mapper import FixedPointVolumeRayCastMapper
from .mapper import GPUVolumeRayCastMapper
from .mapper import OpenGLGPUVolumeRayCastMapper
from .mapper import PointGaussianMapper
from .mapper import SmartVolumeMapper
from .mapper import UnstructuredGridVolumeRayCastMapper
from .picking import PickingHelper
from .render_window_interactor import RenderWindowInteractor
from .renderer import Camera
from .renderer import Renderer
from .renderers import Renderers
from .scalar_bars import ScalarBars
from .text import CornerAnnotation
from .text import Text
from .text import TextProperty
from .texture import numpy_to_texture
from .themes import Theme
from .tools import normalize # noqa: F401
from .tools import opacity_transfer_function # noqa: F401
from .tools import parse_font_family # noqa: F401
from .utilities.algorithms import active_scalars_algorithm
from .utilities.algorithms import algorithm_to_mesh_handler
from .utilities.algorithms import decimation_algorithm
from .utilities.algorithms import extract_surface_algorithm
from .utilities.algorithms import pointset_to_polydata_algorithm
from .utilities.algorithms import set_algorithm_input
from .utilities.algorithms import triangulate_algorithm
from .utilities.gl_checks import uses_egl
from .utilities.regression import image_from_window
from .utilities.regression import run_image_filter
from .volume import Volume
from .volume_property import VolumeProperty
from .widgets import WidgetHelper
if TYPE_CHECKING: # pragma: no cover
from pyvista.core._typing_core import BoundsLike
SUPPORTED_FORMATS = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"]
# EXPERIMENTAL: permit pyvista to kill the render window
KILL_DISPLAY = platform.system() == 'Linux' and os.environ.get('PYVISTA_KILL_DISPLAY')
if KILL_DISPLAY: # pragma: no cover
# this won't work under wayland
try:
X11 = ctypes.CDLL("libX11.so")
X11.XCloseDisplay.argtypes = [ctypes.c_void_p]
except OSError:
warnings.warn('PYVISTA_KILL_DISPLAY: Unable to load X11.\nProbably using wayland')
KILL_DISPLAY = False
def close_all():
"""Close all open/active plotters and clean up memory.
Returns
-------
bool
``True`` when all plotters have been closed.
"""
for pl in list(_ALL_PLOTTERS.values()):
if not pl._closed:
pl.close()
_ALL_PLOTTERS.clear()
return True
log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
log.addHandler(logging.StreamHandler())
def _warn_xserver(): # pragma: no cover
"""Check if plotting is supported and persist this state.
Check once and cache this value between calls. Warn the user if
plotting is not supported. Configured to check on Linux and Mac
OS since the Windows check is not quick.
"""
# disable windows check until we can get a fast way of verifying
# if windows has a windows manager (which it generally does)
if os.name == 'nt':
return
if not hasattr(_warn_xserver, 'has_support'):
_warn_xserver.has_support = pyvista.system_supports_plotting()
if not _warn_xserver.has_support:
# check if a display has been set
if 'DISPLAY' in os.environ:
return
# finally, check if using a backend that doesn't require an xserver
if pyvista.global_theme.jupyter_backend in [
'client',
'html',
]:
return
# Check if VTK has EGL support
if uses_egl():
return
warnings.warn(
'\n'
'This system does not appear to be running an xserver.\n'
'PyVista will likely segfault when rendering.\n\n'
'Try starting a virtual frame buffer with xvfb, or using\n '
' ``pyvista.start_xvfb()``\n',
)
@abstract_class
class BasePlotter(PickingHelper, WidgetHelper):
"""Base plotting class.
To be used by the :class:`pyvista.Plotter` and
:class:`pyvistaqt.QtInteractor` classes.
Parameters
----------
shape : sequence[int] | str, optional
Two item sequence of sub-render windows inside of the main window.
Specify two across with ``shape=(2, 1)`` and a two by two grid
with ``shape=(2, 2)``. By default there is only one renderer.
Can also accept a string descriptor as shape. For example:
* ``shape="3|1"`` means 3 plots on the left and 1 on the right,
* ``shape="4/2"`` means 4 plots on top and 2 at the bottom.
border : bool, default: False
Draw a border around each render window.
border_color : ColorLike, default: 'k'
Either a string, rgb list, or hex color string. For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
border_width : float, default: 2.0
Width of the border in pixels when enabled.
title : str, optional
Window title.
splitting_position : float, optional
The splitting position of the renderers.
groups : tuple, optional
Grouping for renderers.
row_weights : tuple
Row weights for renderers.
col_weights : tuple, optional
Column weights for renderers.
lighting : str, default: 'light kit'
What lighting to set up for the plotter. Accepted options:
* ``'light_kit'``: a vtk Light Kit composed of 5 lights.
* ``'three lights'``: illumination using 3 lights.
* ``'none'``: no light sources at instantiation.
theme : pyvista.plotting.themes.Theme, optional
Plot-specific theme.
image_scale : int, optional
Scale factor when saving screenshots. Image sizes will be
the ``window_size`` multiplied by this scale factor.
**kwargs : dict, optional
Additional keyword arguments.
Examples
--------
Simple plotter example showing a blurred cube with a gradient background.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.set_background('black', top='white')
>>> pl.add_blurring()
>>> pl.show()
"""
mouse_position = None
click_position = None
def __init__(
self,
shape=(1, 1),
border=None,
border_color='k',
border_width=2.0,
title=None,
splitting_position=None,
groups=None,
row_weights=None,
col_weights=None,
lighting='light kit',
theme=None,
image_scale=None,
**kwargs,
):
"""Initialize base plotter."""
super().__init__(**kwargs) # cooperative multiple inheritance
log.debug('BasePlotter init start')
self._initialized = False
self._theme = Theme()
if theme is None:
# copy global theme to ensure local plot theme is fixed
# after creation.
self._theme.load_theme(pyvista.global_theme)
else:
if not isinstance(theme, pyvista.plotting.themes.Theme):
raise TypeError(
'Expected ``pyvista.plotting.themes.Theme`` for '
f'``theme``, not {type(theme).__name__}.',
)
self._theme.load_theme(theme)
self.image_transparent_background = self._theme.transparent_background
# optional function to be called prior to closing
self.__before_close_callback = None
self.mesh = None
if title is None:
title = self._theme.title
self.title = str(title)
# add renderers
self.renderers = Renderers(
self,
shape,
splitting_position,
row_weights,
col_weights,
groups,
border,
border_color,
border_width,
)
# This keeps track of scalars names already plotted and their ranges
self._scalar_bars = ScalarBars(self)
# track if the camera has been set up
self._first_time = True
# Keep track of the scale
# track if render window has ever been rendered
self._rendered = False
self._on_render_callbacks = set()
# this helps managing closed plotters
self._closed = False
# lighting style; be forgiving with input (accept underscores
# and ignore case)
lighting_normalized = str(lighting).replace('_', ' ').lower()
if lighting_normalized == 'light kit':
self.enable_lightkit()
elif lighting_normalized == 'three lights':
self.enable_3_lights()
elif lighting_normalized != 'none':
raise ValueError(f'Invalid lighting option "{lighting}".')
# Track all active plotters. This has the side effect of ensuring that plotters are not
# collected until `close()`. See https://github.com//pull/3216
# This variable should be safe as a variable name
self._id_name = f"P_{hex(id(self))}_{len(_ALL_PLOTTERS)}"
_ALL_PLOTTERS[self._id_name] = self
# Key bindings
self.reset_key_events()
log.debug('BasePlotter init stop')
self._image_depth_null = None
self.last_image_depth = None
self.last_image = None
self.last_vtksz = None
self._has_background_layer = False
if image_scale is None:
image_scale = self._theme.image_scale
self._image_scale = image_scale
# set hidden line removal based on theme
if self.theme.hidden_line_removal:
self.enable_hidden_line_removal()
self._initialized = True
self._suppress_rendering = False
@property
def suppress_rendering(self): # numpydoc ignore=RT01
"""Get or set whether to suppress render calls.
Returns
-------
bool
``True`` when rendering is suppressed.
"""
return self._suppress_rendering
@suppress_rendering.setter
def suppress_rendering(self, value): # numpydoc ignore=GL08
self._suppress_rendering = bool(value)
@property
def render_window(self): # numpydoc ignore=RT01
"""Access the vtkRenderWindow attached to this plotter.
If the plotter is closed, this will return ``None``.
Returns
-------
vtk.vtkRenderWindow or None
Render window if the plotter is not closed.
Notes
-----
Subclass must set ``ren_win`` on initialization.
"""
if not hasattr(self, 'ren_win'):
return None
return self.ren_win
@property
def theme(self): # numpydoc ignore=RT01
"""Return or set the theme used for this plotter.
Returns
-------
pyvista.Theme
Theme of this plotter.
Examples
--------
Use the dark theme for a plotter.
>>> import pyvista as pv
>>> from pyvista import themes
>>> pl = pv.Plotter()
>>> pl.theme = themes.DarkTheme()
>>> actor = pl.add_mesh(pv.Sphere())
>>> pl.show()
"""
return self._theme
@theme.setter
def theme(self, theme): # numpydoc ignore=GL08
if not isinstance(theme, pyvista.plotting.themes.Theme):
raise TypeError(
'Expected a pyvista theme like '
'``pyvista.plotting.themes.Theme``, '
f'not {type(theme).__name__}.',
)
self._theme.load_theme(theme)
def import_gltf(self, filename, set_camera=True):
"""Import a glTF file into the plotter.
See https://www.khronos.org/gltf/ for more information.
Parameters
----------
filename : str | Path
Path to the glTF file.
set_camera : bool, default: True
Set the camera viewing angle to one compatible with the
default three.js perspective (``'xy'``).
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> helmet_file = (
... examples.gltf.download_damaged_helmet()
... ) # doctest:+SKIP
>>> texture = (
... examples.hdr.download_dikhololo_night()
... ) # doctest:+SKIP
>>> pl = pv.Plotter() # doctest:+SKIP
>>> pl.import_gltf(helmet_file) # doctest:+SKIP
>>> pl.set_environment_texture(cubemap) # doctest:+SKIP
>>> pl.camera.zoom(1.8) # doctest:+SKIP
>>> pl.show() # doctest:+SKIP
See :ref:`load_gltf` for a full example using this method.
"""
filename = Path(filename).expanduser().resolve()
if not filename.is_file():
raise FileNotFoundError(f'Unable to locate {filename}')
# lazy import here to avoid importing unused modules
from vtkmodules.vtkIOImport import vtkGLTFImporter
importer = vtkGLTFImporter()
if pyvista.vtk_version_info < (9, 2, 2): # pragma no cover
importer.SetFileName(str(filename))
else:
importer.SetFileName(filename)
importer.SetRenderWindow(self.render_window)
importer.Update()
# register last actor in actors
actor = self.renderer.GetActors().GetLastItem()
name = actor.GetAddressAsString("")
self.renderer._actors[name] = actor
# set camera position to a three.js viewing perspective
if set_camera:
self.camera_position = 'xy'
def import_vrml(self, filename):
"""Import a VRML file into the plotter.
Parameters
----------
filename : str | Path
Path to the VRML file.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> sextant_file = (
... examples.vrml.download_sextant()
... ) # doctest:+SKIP
>>> pl = pv.Plotter() # doctest:+SKIP
>>> pl.import_vrml(sextant_file) # doctest:+SKIP
>>> pl.show() # doctest:+SKIP
See :ref:`load_vrml_example` for a full example using this method.
"""
from vtkmodules.vtkIOImport import vtkVRMLImporter
filename = Path(filename).expanduser().resolve()
if not filename.is_file():
raise FileNotFoundError(f'Unable to locate {filename}')
# lazy import here to avoid importing unused modules
importer = vtkVRMLImporter()
if pyvista.vtk_version_info < (9, 2, 2): # pragma no cover
importer.SetFileName(str(filename))
else:
importer.SetFileName(filename)
importer.SetRenderWindow(self.render_window)
importer.Update()
def import_3ds(self, filename):
"""Import a 3DS file into the plotter.
.. versionadded:: 0.44.0
Parameters
----------
filename : str | Path
Path to the 3DS file.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> download_3ds_file = examples.download_3ds.download_iflamigm()
>>> pl = pv.Plotter()
>>> pl.import_3ds(download_3ds_file)
>>> pl.show()
"""
from vtkmodules.vtkIOImport import vtk3DSImporter
filename = Path(filename).expanduser().resolve()
if not Path(filename).is_file():
raise FileNotFoundError(f'Unable to locate {filename}')
# lazy import here to avoid importing unused modules
importer = vtk3DSImporter()
if pyvista.vtk_version_info < (9, 2, 2): # pragma no cover
importer.SetFileName(str(filename))
else:
importer.SetFileName(filename)
importer.SetRenderWindow(self.render_window)
importer.Update()
def import_obj(self, filename, filename_mtl=None):
"""Import from .obj wavefront files.
.. versionadded:: 0.44.0
Parameters
----------
filename : str | Path
Path to the .obj file.
filename_mtl : str, optional
Path to the .mtl file.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> download_obj_file = examples.download_room_surface_mesh(
... load=False
... )
>>> pl = pv.Plotter()
>>> pl.import_obj(download_obj_file)
>>> pl.show()
Import an .obj file with a texture.
>>> from pathlib import Path
>>> filename = examples.download_doorman(load=False)
>>> pl = pv.Plotter()
>>> pl.import_obj(filename)
>>> pl.show(cpos="xy")
"""
from vtkmodules.vtkIOImport import vtkOBJImporter
filename = Path(filename).expanduser().resolve()
if not filename.is_file():
raise FileNotFoundError(f'Unable to locate {filename}')
# lazy import here to avoid importing unused modules
importer = vtkOBJImporter()
importer.SetFileName(filename)
filename_mtl = filename.with_suffix('.mtl')
if filename_mtl.is_file():
importer.SetFileNameMTL(filename_mtl)
importer.SetTexturePath(filename_mtl.parents[0])
importer.SetRenderWindow(self.render_window)
importer.Update()
def export_html(self, filename):
"""Export this plotter as an interactive scene to a HTML file.
Parameters
----------
filename : str | Path
Path to export the html file to.
Returns
-------
StringIO
If filename is None, returns the HTML as a StringIO object.
Notes
-----
You will need ``trame`` installed.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.load_uniform()
>>> pl = pv.Plotter(shape=(1, 2))
>>> _ = pl.add_mesh(
... mesh, scalars='Spatial Point Data', show_edges=True
... )
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(
... mesh, scalars='Spatial Cell Data', show_edges=True
... )
>>> pl.export_html('pv.html') # doctest:+SKIP
"""
try:
from trame_vtk.tools.vtksz2html import write_html
except ImportError: # pragma: no cover
raise ImportError('Please install trame-vtk to export')
data = self.export_vtksz(filename=None)
buffer = io.StringIO()
write_html(data, buffer)
buffer.seek(0)
if filename is None:
return buffer
filename = Path(filename)
if filename.suffix != ".html":
filename += '.html'
# Move to final destination
with Path(filename).open('w', encoding='utf-8') as f:
f.write(buffer.read())
return None
def export_vtksz(self, filename='scene-export.vtksz', format='zip'): # noqa: A002
"""Export this plotter as a VTK.js OfflineLocalView file.
The exported file can be viewed with the OfflineLocalView viewer
available at https://kitware.github.io/vtk-js/examples/OfflineLocalView.html
Parameters
----------
filename : str | Path, optional
Path to export the file to. Defaults to ``'scene-export.vtksz'``.
format : str, optional
The format of the exported file. Defaults to ``'zip'``. Can be
either ``'zip'`` or ``'json'``.
Returns
-------
str
The exported filename.
"""
try:
from pyvista.trame import PyVistaLocalView
from pyvista.trame.jupyter import elegantly_launch
from pyvista.trame.views import get_server
except ImportError: # pragma: no cover
raise ImportError('Please install trame to export')
# Ensure trame server is launched
server = get_server(pyvista.global_theme.trame.jupyter_server_name)
if not server.running:
elegantly_launch(pyvista.global_theme.trame.jupyter_server_name)
view = PyVistaLocalView(self, trame_server=server)
content = view.export(format=format)
view.release_resources()
# Make sure callbacks are unregistered
self._on_render_callbacks.remove(view._plotter_render_callback)
if filename is None:
return content
with Path(filename).open('wb') as f:
f.write(content)
return filename
def export_gltf(self, filename, inline_data=True, rotate_scene=True, save_normals=True):
"""Export the current rendering scene as a glTF file.
Visit https://gltf-viewer.donmccurdy.com/ for an online viewer.
See https://vtk.org/doc/nightly/html/classvtkGLTFExporter.html
for limitations regarding the exporter.
Parameters
----------
filename : str
Path to export the gltf file to.
inline_data : bool, default: True
Sets if the binary data be included in the json file as a
base64 string. When ``True``, only one file is exported.
rotate_scene : bool, default: True
Rotate scene to be compatible with the glTF specifications.
save_normals : bool, default: True
Saves the point array ``'Normals'`` as ``'NORMAL'`` in
the outputted scene.
Notes
-----
The VTK exporter only supports :class:`pyvista.PolyData` datasets. If
the plotter contains any non-PolyData datasets, these will be converted
in the plotter, leading to a copy of the data internally.
Examples
--------
Output a simple point cloud represented as balls.
>>> import numpy as np
>>> import pyvista as pv
>>> rng = np.random.default_rng(seed=0)
>>> point_cloud = rng.random((100, 3))
>>> pdata = pv.PolyData(point_cloud)
>>> pdata['orig_sphere'] = np.arange(100)
>>> sphere = pv.Sphere(radius=0.02)
>>> pc = pdata.glyph(scale=False, geom=sphere, orient=False)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(
... pc,
... cmap='reds',
... smooth_shading=True,
... show_scalar_bar=False,
... )
>>> pl.export_gltf('balls.gltf') # doctest:+SKIP
>>> pl.show()
Output the orientation plotter.
>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.export_gltf('orientation_plotter.gltf') # doctest:+SKIP
>>> pl.show()
"""
if self.render_window is None:
raise RuntimeError('This plotter has been closed and is unable to export the scene.')
from vtkmodules.vtkIOExport import vtkGLTFExporter
# rotate scene to gltf compatible view
renamed_arrays = [] # any renamed normal arrays
if rotate_scene:
for renderer in self.renderers:
for actor in renderer.actors.values():
if hasattr(actor, 'RotateX'):
actor.RotateX(-90)
actor.RotateZ(-90)
if save_normals:
try:
mapper = actor.GetMapper()
if mapper is None:
continue
dataset = mapper.dataset
if not isinstance(dataset, pyvista.PolyData):
warnings.warn(
'Plotter contains non-PolyData datasets. These have been '
'overwritten with PolyData surfaces and are internally '
'copies of the original datasets.',
)
try:
dataset = dataset.extract_surface()
mapper.SetInputData(dataset)
except: # pragma: no cover
warnings.warn(
'During gLTF export, failed to convert some '
'datasets to PolyData. Exported scene will not have '
'all datasets.',
)
if 'Normals' in dataset.point_data:
# By default VTK uses the 'Normals' point data for normals
# but gLTF uses NORMAL.
point_data = dataset.GetPointData()
array = point_data.GetArray('Normals')
array.SetName('NORMAL')
renamed_arrays.append(array)
except: # pragma: no cover
pass
exporter = vtkGLTFExporter()
exporter.SetRenderWindow(self.render_window)
exporter.SetFileName(filename)
exporter.SetInlineData(inline_data)
exporter.SetSaveNormal(save_normals)
exporter.Update()
# rotate back if applicable
if rotate_scene:
for renderer in self.renderers:
for actor in renderer.actors.values():
if hasattr(actor, 'RotateX'):
actor.RotateZ(90)
actor.RotateX(90)
# revert any renamed arrays
for array in renamed_arrays:
array.SetName('Normals')
def export_vrml(self, filename):
"""Export the current rendering scene as a VRML file.
See `vtk.VRMLExporter <https://vtk.org/doc/nightly/html/classvtkVRMLExporter.html>`_
for limitations regarding the exporter.
Parameters
----------
filename : str | Path
Filename to export the scene to.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(examples.load_hexbeam())
>>> pl.export_vrml("sample") # doctest:+SKIP
"""
from vtkmodules.vtkIOExport import vtkVRMLExporter
if self.render_window is None:
raise RuntimeError("This plotter has been closed and cannot be shown.")
exporter = vtkVRMLExporter()
exporter.SetFileName(filename)
exporter.SetRenderWindow(self.render_window)
exporter.Write()
def enable_hidden_line_removal(self, all_renderers=True):
"""Enable hidden line removal.
Wireframe geometry will be drawn using hidden line removal if
the rendering engine supports it.
Disable this with :func:`disable_hidden_line_removal
<Plotter.disable_hidden_line_removal>`.
Parameters
----------
all_renderers : bool, default: True
If ``True``, applies to all renderers in subplots. If
``False``, then only applies to the active renderer.
Examples
--------
Create a side-by-side plotter and render a sphere in wireframe
with hidden line removal enabled on the left and disabled on
the right.
>>> import pyvista as pv
>>> sphere = pv.Sphere(theta_resolution=20, phi_resolution=20)
>>> pl = pv.Plotter(shape=(1, 2))
>>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
>>> _ = pl.add_text("With hidden line removal")
>>> pl.enable_hidden_line_removal(all_renderers=False)
>>> pl.subplot(0, 1)
>>> pl.disable_hidden_line_removal(all_renderers=False)
>>> _ = pl.add_mesh(sphere, line_width=3, style='wireframe')
>>> _ = pl.add_text("Without hidden line removal")
>>> pl.show()
"""
if all_renderers:
for renderer in self.renderers:
renderer.enable_hidden_line_removal()
else:
self.renderer.enable_hidden_line_removal()
def disable_hidden_line_removal(self, all_renderers=True):
"""Disable hidden line removal.
Enable again with :func:`enable_hidden_line_removal
<Plotter.enable_hidden_line_removal>`.
Parameters
----------
all_renderers : bool, default: True
If ``True``, applies to all renderers in subplots. If
``False``, then only applies to the active renderer.
Examples
--------
Enable and then disable hidden line removal.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.enable_hidden_line_removal()
>>> pl.disable_hidden_line_removal()
"""
if all_renderers:
for renderer in self.renderers:
renderer.disable_hidden_line_removal()
else:
self.renderer.disable_hidden_line_removal()
@property
def scalar_bar(self): # numpydoc ignore=RT01
"""First scalar bar (kept for backwards compatibility).
Returns
-------
vtk.vtkScalarBarActor
First scalar bar actor.
"""
return next(iter(self.scalar_bars.values()))
@property
def scalar_bars(self): # numpydoc ignore=RT01
"""Scalar bars.
Returns
-------
pyvista.ScalarBars
Scalar bar object.
Examples
--------
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere['Data'] = sphere.points[:, 2]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere)
>>> plotter.scalar_bars
Scalar Bar Title Interactive
"Data" False
Select a scalar bar actor based on the title of the bar.
>>> plotter.scalar_bars['Data']
<vtkmodules.vtkRenderingAnnotation.vtkScalarBarActor(...) at ...>
"""
return self._scalar_bars
@property
def _before_close_callback(self):
"""Return the cached function (expecting a reference)."""
if self.__before_close_callback is not None:
return self.__before_close_callback()
return None
@_before_close_callback.setter
def _before_close_callback(self, func):
"""Store a weakref.ref of the function being called."""
if func is not None:
self.__before_close_callback = weakref.ref(func)
else:
self.__before_close_callback = None
@property
def shape(self) -> tuple[int] | tuple[int, int]:
"""Return the shape of the plotter.
Returns
-------
tuple[int] | tuple[int, int]
Shape of the plotter.
Examples
--------
Return the plotter shape.
>>> import pyvista as pv
>>> plotter = pv.Plotter(shape=(2, 2))
>>> plotter.shape
(2, 2)
"""
return self.renderers.shape
@property
def renderer(self): # numpydoc ignore=RT01
"""Return the active renderer.
Returns
-------
pyvista.Renderer
Active render.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.renderer
<Renderer(...) at ...>
"""
return self.renderers.active_renderer
def subplot(self, index_row, index_column=None):
"""Set the active subplot.
Parameters
----------
index_row : int
Index of the subplot to activate along the rows.
index_column : int, optional
Index of the subplot to activate along the columns.
Examples
--------
Create a 2 wide plot and set the background of right-hand plot
to orange. Add a cube to the left plot and a sphere to the
right.
>>> import pyvista as pv
>>> pl = pv.Plotter(shape=(1, 2))
>>> actor = pl.add_mesh(pv.Cube())
>>> pl.subplot(0, 1)
>>> actor = pl.add_mesh(pv.Sphere())
>>> pl.set_background('orange', all_renderers=False)
>>> pl.show()
"""
self.renderers.set_active_renderer(index_row, index_column)
@wraps(Renderer.add_ruler)
def add_ruler(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_ruler``."""
return self.renderer.add_ruler(*args, **kwargs)
@wraps(Renderer.add_legend_scale)
def add_legend_scale(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_legend_scale``."""
return self.renderer.add_legend_scale(*args, **kwargs)
@wraps(Renderer.add_legend)
def add_legend(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_legend``."""
return self.renderer.add_legend(*args, **kwargs)
@wraps(Renderer.remove_legend)
def remove_legend(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_legend``."""
return self.renderer.remove_legend(*args, **kwargs)
@property
def legend(self): # numpydoc ignore=RT01
"""Legend actor.
There can only be one legend actor per renderer. If
``legend`` is ``None``, there is no legend actor.
Returns
-------
vtk.vtkLegendBoxActor
Legend actor.
"""
return self.renderer.legend
@wraps(Renderer.add_floor)
def add_floor(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_floor``."""
return self.renderer.add_floor(*args, **kwargs)
@wraps(Renderer.remove_floors)
def remove_floors(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_floors``."""
return self.renderer.remove_floors(*args, **kwargs)
def enable_3_lights(self, only_active=False):
"""Enable 3-lights illumination.
This will replace all pre-existing lights in the scene.
Parameters
----------
only_active : bool, default: False
If ``True``, only change the active renderer. The default
is that every renderer is affected.
Examples
--------
>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.enable_3_lights()
>>> pl.show()
Note how this varies from the default plotting.
>>> pl = demos.orientation_plotter()
>>> pl.show()
"""
def _to_pos(elevation, azimuth):
theta = azimuth * np.pi / 180.0
phi = (90.0 - elevation) * np.pi / 180.0
x = np.sin(theta) * np.sin(phi)
y = np.cos(phi)
z = np.cos(theta) * np.sin(phi)
return x, y, z
renderers = [self.renderer] if only_active else self.renderers
for renderer in renderers:
renderer.remove_all_lights()
# Inspired from Mayavi's version of Raymond Maple 3-lights illumination
intensities = [1, 0.6, 0.5]
all_angles = [(45.0, 45.0), (-30.0, -60.0), (-30.0, 60.0)]
for intensity, angles in zip(intensities, all_angles):
light = pyvista.Light(light_type='camera light')
light.intensity = intensity
light.position = _to_pos(*angles)
for renderer in renderers:
renderer.add_light(light)
def disable_3_lights(self):
"""Please use ``enable_lightkit``, this method has been deprecated."""
from pyvista.core.errors import DeprecationError
raise DeprecationError('DEPRECATED: Please use ``enable_lightkit``')
def enable_lightkit(self, only_active=False):
"""Enable the default light-kit lighting.
See:
https://www.researchgate.net/publication/2926068_LightKit_A_lighting_system_for_effective_visualization
This will replace all pre-existing lights in the renderer.
Parameters
----------
only_active : bool, default: False
If ``True``, only change the active renderer. The default is that
every renderer is affected.
Examples
--------
Create a plotter without any lights and then enable the
default light kit.
>>> import pyvista as pv
>>> pl = pv.Plotter(lighting=None)
>>> pl.enable_lightkit()
>>> actor = pl.add_mesh(pv.Cube(), show_edges=True)
>>> pl.show()
"""
renderers = [self.renderer] if only_active else self.renderers
light_kit = _vtk.vtkLightKit()
for renderer in renderers:
renderer.remove_all_lights()
# Use the renderer as a vtkLightKit parser.
# Feed it the LightKit, pop off the vtkLights, put back
# pyvista Lights. This is the price we must pay for using
# inheritance rather than composition.
light_kit.AddLightsToRenderer(renderer)
vtk_lights = renderer.lights
renderer.remove_all_lights()
for vtk_light in vtk_lights:
light = pyvista.Light.from_vtk(vtk_light)
renderer.add_light(light)
renderer.LightFollowCameraOn()
def enable_anti_aliasing(self, aa_type='ssaa', multi_samples=None, all_renderers=True):
"""Enable anti-aliasing.
This tends to make edges appear softer and less pixelated.
Parameters
----------
aa_type : str, default: "ssaa"
Anti-aliasing type. See the notes below. One of the following:
* ``"ssaa"`` - Super-Sample Anti-Aliasing
* ``"msaa"`` - Multi-Sample Anti-Aliasing
* ``"fxaa"`` - Fast Approximate Anti-Aliasing
multi_samples : int, optional
The number of multi-samples when ``aa_type`` is ``"msaa"``. Note
that using this setting automatically enables this for all
renderers. Defaults to the theme multi_samples.
all_renderers : bool, default: True
If ``True``, applies to all renderers in subplots. If ``False``,
then only applies to the active renderer.
Notes
-----
SSAA, or Super-Sample Anti-Aliasing is a brute force method of
anti-aliasing. It results in the best image quality but comes at a
tremendous resource cost. SSAA works by rendering the scene at a higher
resolution. The final image is produced by downsampling the
massive source image using an averaging filter. This acts as a low pass
filter which removes the high frequency components that would cause
jaggedness.
MSAA, or Multi-Sample Anti-Aliasing is an optimization of SSAA that
reduces the amount of pixel shader evaluations that need to be computed
by focusing on overlapping regions of the scene. The result is
anti-aliasing along edges that is on par with SSAA and less
anti-aliasing along surfaces as these make up the bulk of SSAA
computations. MSAA is substantially less computationally expensive than
SSAA and results in comparable image quality.
FXAA, or Fast Approximate Anti-Aliasing is an Anti-Aliasing technique
that is performed entirely in post processing. FXAA operates on the
rasterized image rather than the scene geometry. As a consequence,
forcing FXAA or using FXAA incorrectly can result in the FXAA filter
smoothing out parts of the visual overlay that are usually kept sharp
for reasons of clarity as well as smoothing out textures. FXAA is
inferior to MSAA but is almost free computationally and is thus
desirable on low end platforms.
Examples
--------
Enable super-sample anti-aliasing (SSAA).
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.enable_anti_aliasing('ssaa')
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.show()
See :ref:`anti_aliasing_example` for a full example demonstrating
VTK's anti-aliasing approaches.
"""
# apply MSAA to entire render window
if aa_type == 'msaa':
if self.render_window is None:
raise AttributeError('The render window has been closed.')
if multi_samples is None:
multi_samples = self._theme.multi_samples
self.render_window.SetMultiSamples(multi_samples)
return
elif aa_type not in ['ssaa', 'fxaa']:
raise ValueError(
f'Invalid `aa_type` "{aa_type}". Should be either "fxaa", "ssaa", or "msaa"',
)
else:
# disable MSAA as SSAA or FXAA is being enabled
self.render_window.SetMultiSamples(0)
if all_renderers:
for renderer in self.renderers:
renderer.enable_anti_aliasing(aa_type)
else:
self.renderer.enable_anti_aliasing(aa_type)
def disable_anti_aliasing(self, all_renderers=True):
"""Disable anti-aliasing.
Parameters
----------
all_renderers : bool, default: True
If ``True``, applies to all renderers in subplots. If ``False``,
then only applies to the active renderer.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.disable_anti_aliasing()
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.show()
See :ref:`anti_aliasing_example` for a full example demonstrating
VTK's anti-aliasing approaches.
"""
self.render_window.SetMultiSamples(0)
if all_renderers:
for renderer in self.renderers:
renderer.disable_anti_aliasing()
else:
self.renderer.disable_anti_aliasing()
@wraps(Renderer.set_focus)
def set_focus(self, *args, render=True, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.set_focus``."""
log.debug('set_focus: %s, %s', str(args), str(kwargs))
self.renderer.set_focus(*args, **kwargs)
if render:
self.render()
@wraps(Renderer.set_position)
def set_position(self, *args, render=True, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.set_position``."""
self.renderer.set_position(*args, **kwargs)
if render:
self.render()
@wraps(Renderer.set_viewup)
def set_viewup(self, *args, render=True, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.set_viewup``."""
self.renderer.set_viewup(*args, **kwargs)
if render:
self.render()
@wraps(Renderer.add_orientation_widget)
def add_orientation_widget(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_orientation_widget``."""
return self.renderer.add_orientation_widget(*args, **kwargs)
@wraps(Renderer.add_axes)
def add_axes(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_axes``."""
return self.renderer.add_axes(*args, **kwargs)
@wraps(Renderer.add_box_axes)
def add_box_axes(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_box_axes``."""
return self.renderer.add_box_axes(*args, **kwargs)
@wraps(Renderer.add_north_arrow_widget)
def add_north_arrow_widget(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_north_arrow_widget``."""
return self.renderer.add_north_arrow_widget(*args, **kwargs)
@wraps(Renderer.hide_axes)
def hide_axes(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.hide_axes``."""
return self.renderer.hide_axes(*args, **kwargs)
@wraps(Renderer.show_axes)
def show_axes(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.show_axes``."""
return self.renderer.show_axes(*args, **kwargs)
@wraps(Renderer.update_bounds_axes)
def update_bounds_axes(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.update_bounds_axes``."""
return self.renderer.update_bounds_axes(*args, **kwargs)
@wraps(Renderer.add_chart)
def add_chart(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_chart``."""
return self.renderer.add_chart(*args, **kwargs)
@wraps(Renderer.remove_chart)
def remove_chart(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_chart``."""
return self.renderer.remove_chart(*args, **kwargs)
@wraps(Renderers.set_chart_interaction)
def set_chart_interaction(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderers.set_chart_interaction``."""
return self.renderers.set_chart_interaction(*args, **kwargs)
@wraps(Renderer.add_actor)
def add_actor(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_actor``."""
return self.renderer.add_actor(*args, **kwargs)
@wraps(Renderer.enable_parallel_projection)
def enable_parallel_projection(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable_parallel_projection``."""
return self.renderer.enable_parallel_projection(*args, **kwargs)
@wraps(Renderer.disable_parallel_projection)
def disable_parallel_projection(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable_parallel_projection``."""
return self.renderer.disable_parallel_projection(*args, **kwargs)
@wraps(Renderer.enable_ssao)
def enable_ssao(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable_ssao``."""
return self.renderer.enable_ssao(*args, **kwargs)
@wraps(Renderer.disable_ssao)
def disable_ssao(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable_ssao``."""
return self.renderer.disable_ssao(*args, **kwargs)
@wraps(Renderer.enable_shadows)
def enable_shadows(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable_shadows``."""
return self.renderer.enable_shadows(*args, **kwargs)
@wraps(Renderer.disable_shadows)
def disable_shadows(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable_shadows``."""
return self.renderer.disable_shadows(*args, **kwargs)
@property
def parallel_projection(self): # numpydoc ignore=RT01
"""Return or set parallel projection state of active render window."""
return self.renderer.parallel_projection
@parallel_projection.setter
def parallel_projection(self, state): # numpydoc ignore=GL08
self.renderer.parallel_projection = state
@property
def parallel_scale(self): # numpydoc ignore=RT01
"""Return or set parallel scale of active render window."""
return self.renderer.parallel_scale
@parallel_scale.setter
def parallel_scale(self, value): # numpydoc ignore=GL08
self.renderer.parallel_scale = value
@wraps(Renderer.add_axes_at_origin)
def add_axes_at_origin(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_axes_at_origin``."""
return self.renderer.add_axes_at_origin(*args, **kwargs)
@wraps(Renderer.show_bounds)
def show_bounds(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.show_bounds``."""
return self.renderer.show_bounds(*args, **kwargs)
@wraps(Renderer.add_bounding_box)
def add_bounding_box(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_bounding_box``."""
return self.renderer.add_bounding_box(*args, **kwargs)
@wraps(Renderer.remove_bounding_box)
def remove_bounding_box(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_bounding_box``."""
return self.renderer.remove_bounding_box(*args, **kwargs)
@wraps(Renderer.remove_bounds_axes)
def remove_bounds_axes(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_bounds_axes``."""
return self.renderer.remove_bounds_axes(*args, **kwargs)
@wraps(Renderer.show_grid)
def show_grid(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.show_grid``."""
return self.renderer.show_grid(*args, **kwargs)
@wraps(Renderer.set_scale)
def set_scale(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.set_scale``."""
return self.renderer.set_scale(*args, **kwargs)
@wraps(Renderer.enable_depth_of_field)
def enable_depth_of_field(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable_depth_of_field``."""
return self.renderer.enable_depth_of_field(*args, **kwargs)
@wraps(Renderer.disable_depth_of_field)
def disable_depth_of_field(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable_depth_of_field``."""
return self.renderer.disable_depth_of_field(*args, **kwargs)
@wraps(Renderer.add_blurring)
def add_blurring(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.add_blurring``."""
return self.renderer.add_blurring(*args, **kwargs)
@wraps(Renderer.remove_blurring)
def remove_blurring(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_blurring``."""
return self.renderer.remove_blurring(*args, **kwargs)
@wraps(Renderer.enable_eye_dome_lighting)
def enable_eye_dome_lighting(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable_eye_dome_lighting``."""
return self.renderer.enable_eye_dome_lighting(*args, **kwargs)
@wraps(Renderer.disable_eye_dome_lighting)
def disable_eye_dome_lighting(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable_eye_dome_lighting``."""
self.renderer.disable_eye_dome_lighting(*args, **kwargs)
@wraps(Renderer.reset_camera)
def reset_camera(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.reset_camera``."""
self.renderer.reset_camera(*args, **kwargs)
self.render()
@wraps(Renderer.isometric_view)
def isometric_view(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.isometric_view``."""
self.renderer.isometric_view(*args, **kwargs)
@wraps(Renderer.view_isometric)
def view_isometric(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_isometric``."""
self.renderer.view_isometric(*args, **kwarg)
@wraps(Renderer.view_vector)
def view_vector(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_vector``."""
self.renderer.view_vector(*args, **kwarg)
@wraps(Renderer.view_xy)
def view_xy(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_xy``."""
self.renderer.view_xy(*args, **kwarg)
@wraps(Renderer.view_yx)
def view_yx(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_yx``."""
self.renderer.view_yx(*args, **kwarg)
@wraps(Renderer.view_xz)
def view_xz(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_xz``."""
self.renderer.view_xz(*args, **kwarg)
@wraps(Renderer.view_zx)
def view_zx(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_zx``."""
self.renderer.view_zx(*args, **kwarg)
@wraps(Renderer.view_yz)
def view_yz(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_yz``."""
self.renderer.view_yz(*args, **kwarg)
@wraps(Renderer.view_zy)
def view_zy(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.view_zy``."""
self.renderer.view_zy(*args, **kwarg)
@wraps(Renderer.disable)
def disable(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable``."""
self.renderer.disable(*args, **kwarg)
@wraps(Renderer.enable)
def enable(self, *args, **kwarg): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable``."""
self.renderer.enable(*args, **kwarg)
@wraps(Renderer.enable_depth_peeling)
def enable_depth_peeling(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.enable_depth_peeling``."""
if self.render_window is not None:
result = self.renderer.enable_depth_peeling(*args, **kwargs)
if result:
self.render_window.AlphaBitPlanesOn()
return result
return None # pragma: no cover
@wraps(Renderer.disable_depth_peeling)
def disable_depth_peeling(self): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.disable_depth_peeling``."""
if self.render_window is not None:
self.render_window.AlphaBitPlanesOff()
return self.renderer.disable_depth_peeling()
return None # pragma: no cover
@wraps(Renderer.get_default_cam_pos)
def get_default_cam_pos(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.get_default_cam_pos``."""
return self.renderer.get_default_cam_pos(*args, **kwargs)
@wraps(Renderer.remove_actor)
def remove_actor(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_actor``."""
for renderer in self.renderers:
renderer.remove_actor(*args, **kwargs)
return True
@wraps(Renderer.set_environment_texture)
def set_environment_texture(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.set_environment_texture``."""
return self.renderer.set_environment_texture(*args, **kwargs)
@wraps(Renderer.remove_environment_texture)
def remove_environment_texture(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderer.remove_environment_texture``."""
return self.renderer.remove_environment_texture(*args, **kwargs)
#### Properties from Renderer ####
@property
def actors(self): # numpydoc ignore=RT01
"""Return the actors of the active renderer.
Returns
-------
dict
Dictionary of active actors.
"""
return self.renderer.actors
@property
def camera(self): # numpydoc ignore=RT01
"""Return the active camera of the active renderer.
Returns
-------
pyvista.Camera
Camera from the active renderer.
"""
if not self.renderer.camera.is_set:
self.camera_position = self.get_default_cam_pos()
self.reset_camera()
self.renderer.camera.is_set = True
return self.renderer.camera
@camera.setter
def camera(self, camera): # numpydoc ignore=GL08
self.renderer.camera = camera
@property
def camera_set(self): # numpydoc ignore=RT01
"""Return or set if the camera of the active renderer has been set."""
return self.renderer.camera.is_set
@camera_set.setter
def camera_set(self, is_set): # numpydoc ignore=GL08
self.renderer.camera.is_set = is_set
@property
def bounds(self) -> BoundsLike: # numpydoc ignore=RT01
"""Return the bounds of the active renderer.
Returns
-------
tuple[numpy.float64, numpy.float64, numpy.float64, numpy.float64, numpy.float64, numpy.float64]
Bounds of the active renderer.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.bounds
(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)
"""
return self.renderer.bounds
@property
def length(self): # numpydoc ignore=RT01
"""Return the length of the diagonal of the bounding box of the scene."""
return self.renderer.length
@property
def center(self) -> tuple[float, float, float]:
"""Return the center of the active renderer.
Returns
-------
list[numpy.float64, numpy.float64, numpy.float64]
Center of the active renderer.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.center
(0.0, 0.0, 0.0)
"""
return self.renderer.center
@property
def _scalar_bar_slots(self):
"""Return the scalar bar slots of the active renderer."""
return self.renderer._scalar_bar_slots
@_scalar_bar_slots.setter
def _scalar_bar_slots(self, value):
"""Set the scalar bar slots of the active renderer."""
self.renderer._scalar_bar_slots = value
@property
def _scalar_bar_slot_lookup(self):
"""Return the scalar bar slot lookup of the active renderer."""
return self.renderer._scalar_bar_slot_lookup
@_scalar_bar_slot_lookup.setter
def _scalar_bar_slot_lookup(self, value):
self.renderer._scalar_bar_slot_lookup = value
@property
def scale(self): # numpydoc ignore=RT01
"""Return the scaling of the active renderer."""
return self.renderer.scale
@scale.setter
def scale(self, scale): # numpydoc ignore=GL08
self.renderer.set_scale(*scale)
@property
def camera_position(self): # numpydoc ignore=RT01
"""Return camera position of the active render window.
Examples
--------
Return camera's position and then reposition it via a list of tuples.
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.download_bunny_coarse()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True, reset_camera=True)
>>> pl.camera_position
[(0.02430, 0.0336, 0.9446),
(0.02430, 0.0336, -0.02225),
(0.0, 1.0, 0.0)]
>>> pl.camera_position = [
... (0.3914, 0.4542, 0.7670),
... (0.0243, 0.0336, -0.0222),
... (-0.2148, 0.8998, -0.3796),
... ]
>>> pl.show()
Set the camera position using a string and look at the ``'xy'`` plane.
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> pl.camera_position = 'xy'
>>> pl.show()
Set the camera position using a string and look at the ``'zy'`` plane.
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> pl.camera_position = 'zy'
>>> pl.show()
For more examples, see :ref:`cameras_api`.
"""
return self.renderer.camera_position
@camera_position.setter
def camera_position(self, camera_location): # numpydoc ignore=GL08
self.renderer.camera_position = camera_location
@property
def background_color(self): # numpydoc ignore=RT01
"""Return the background color of the active render window.
Examples
--------
Set the background color to ``"pink"`` and plot it.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube(), show_edges=True)
>>> pl.background_color = "pink"
>>> pl.background_color
Color(name='pink', hex='#ffc0cbff', opacity=255)
>>> pl.show()
"""
return self.renderers.active_renderer.background_color
@background_color.setter
def background_color(self, color): # numpydoc ignore=GL08
self.set_background(color)
@property
def window_size(self): # numpydoc ignore=RT01
"""Return the render window size in ``(width, height)``.
Examples
--------
Change the window size from ``200 x 200`` to ``400 x 400``.
>>> import pyvista as pv
>>> pl = pv.Plotter(window_size=[200, 200])
>>> pl.window_size
[200, 200]
>>> pl.window_size = [400, 400]
>>> pl.window_size
[400, 400]
"""
return list(self.render_window.GetSize())
@window_size.setter
def window_size(self, window_size): # numpydoc ignore=GL08
self.render_window.SetSize(window_size[0], window_size[1])
self._window_size_unset = False
self.render()
@contextmanager
def window_size_context(self, window_size=None):
"""Set the render window size in an isolated context.
Parameters
----------
window_size : sequence[int], optional
Window size in pixels. Defaults to :attr:`pyvista.Plotter.window_size`.
Examples
--------
Take two different screenshots with two different window sizes.
>>> import pyvista as pv
>>> pl = pv.Plotter(off_screen=True)
>>> _ = pl.add_mesh(pv.Cube())
>>> with pl.window_size_context((400, 400)):
... pl.screenshot('/tmp/small_screenshot.png') # doctest:+SKIP
...
>>> with pl.window_size_context((1000, 1000)):
... pl.screenshot('/tmp/big_screenshot.png') # doctest:+SKIP
...
"""
# No op if not set
if window_size is None:
yield self
return
# If render window is not current
if self.render_window is None:
warnings.warn('Attempting to set window_size on an unavailable render widow.')
yield self
return
size_before = self.window_size
if window_size is not None:
self.window_size = window_size
try:
yield self
finally:
# Sometimes the render window is destroyed within the context
# and re-setting will fail
if self.render_window is not None:
self.window_size = size_before
@property
def image_depth(self): # numpydoc ignore=RT01
"""Return a depth image representing current render window.
Helper attribute for ``get_image_depth``.
"""
return self.get_image_depth()
def _check_rendered(self):
"""Check if the render window has been shown and raise an exception if not."""
if not self._rendered:
raise AttributeError(
'\nThis plotter has not yet been set up and rendered '
'with ``show()``.\n'
'Consider setting ``off_screen=True`` '
'for off screen rendering.\n',
)
def _check_has_ren_win(self):
"""Check if render window attribute exists and raise an exception if not."""
if self.render_window is None:
raise RenderWindowUnavailable('Render window is not available.')
if not self.render_window.IsCurrent():
raise RenderWindowUnavailable('Render window is not current.')
def _make_render_window_current(self):
if self.render_window is None:
raise RenderWindowUnavailable('Render window is not available.')
self.render_window.MakeCurrent() # pragma: no cover
@property
def image(self): # numpydoc ignore=RT01
"""Return an image array of current render window.
Returns
-------
pyvista.pyvista_ndarray
Image array of current render window.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter(off_screen=True)
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.show()
>>> pl.image # doctest:+SKIP
"""
if self.render_window is None and self.last_image is not None:
return self.last_image
self._check_rendered()
self._check_has_ren_win()
data = image_from_window(self.render_window, scale=self.image_scale)
if self.image_transparent_background:
return data
# ignore alpha channel
return data[:, :, :-1]
@property
def image_scale(self) -> int: # numpydoc ignore=RT01
"""Get or set the scale factor when saving a screenshot.
This will scale up the screenshots taken of the render window to save a
higher resolution image than what is rendered on screen.
Image sizes will be the :py:attr:`window_size
<pyvista.Plotter.window_size>` multiplied by this scale factor.
Returns
-------
int
Image scale factor.
Examples
--------
Double the resolution of a screenshot.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.image_scale = 2
>>> pl.screenshot('screenshot.png') # doctest:+SKIP
Set the image scale from ``Plotter``.
>>> import pyvista as pv
>>> pl = pv.Plotter(image_scale=2)
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.screenshot('screenshot.png') # doctest:+SKIP
"""
return self._image_scale
@image_scale.setter
def image_scale(self, value: int): # numpydoc ignore=GL08
value = int(value)
if value < 1:
raise ValueError('Scale factor must be a positive integer.')
self._image_scale = value
@contextmanager
def image_scale_context(self, scale: int | None = None):
"""Set the image scale in an isolated context.
Parameters
----------
scale : int, optional
Integer scale factor. Defaults to :attr:`pyvista.Plotter.image_scale`.
"""
scale_before = self.image_scale
if scale is not None:
self.image_scale = scale
try:
yield self
finally:
self.image_scale = scale_before
def render(self):
"""Render the main window.
Will not render until ``show`` has been called.
Any render callbacks added with
:func:`add_on_render_callback() <pyvista.Plotter.add_on_render_callback>`
and the ``render_event=False`` option set will still execute on any call.
"""
if self.render_window is not None and not self._first_time and not self._suppress_rendering:
log.debug('Rendering')
self.renderers.on_plotter_render()
self.render_window.Render()
self._rendered = True
for callback in self._on_render_callbacks:
callback(self)
def add_on_render_callback(self, callback, render_event=False):
"""Add a method to be called post-render.
Parameters
----------
callback : callable
The callback method to run post-render. This takes a single
argument which is the plotter object.
render_event : bool, default: False
If ``True``, associate with all VTK RenderEvents. Otherwise, the
callback is only handled on a successful ``render()`` from the
PyVista plotter directly.
"""
if render_event:
for renderer in self.renderers:
renderer.AddObserver(_vtk.vtkCommand.RenderEvent, lambda *args: callback(self))
else:
self._on_render_callbacks.add(callback)
def clear_on_render_callbacks(self):
"""Clear all callback methods previously registered with ``render()``."""
for renderer in self.renderers:
renderer.RemoveObservers(_vtk.vtkCommand.RenderEvent)
self._on_render_callbacks = set()
@wraps(RenderWindowInteractor.add_key_event)
def add_key_event(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.add_key_event."""
if hasattr(self, 'iren'):
self.iren.add_key_event(*args, **kwargs)
@wraps(RenderWindowInteractor.add_timer_event)
def add_timer_event(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.add_timer_event."""
if hasattr(self, 'iren'):
self.iren.add_timer_event(*args, **kwargs)
@wraps(RenderWindowInteractor.clear_events_for_key)
def clear_events_for_key(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.clear_events_for_key."""
if hasattr(self, 'iren'):
self.iren.clear_events_for_key(*args, **kwargs)
def store_mouse_position(self, *args):
"""Store mouse position."""
if not hasattr(self, "iren"):
raise AttributeError("This plotting window is not interactive.")
self.mouse_position = self.iren.get_event_position()
def store_click_position(self, *args):
"""Store click position in viewport coordinates."""
if not hasattr(self, "iren"):
raise AttributeError("This plotting window is not interactive.")
self.click_position = self.iren.get_event_position()
self.mouse_position = self.click_position
def track_mouse_position(self):
"""Keep track of the mouse position.
This will potentially slow down the interactor. No callbacks
supported here - use
:func:`pyvista.Plotter.track_click_position` instead.
"""
self.iren.track_mouse_position(self.store_mouse_position)
def untrack_mouse_position(self):
"""Stop tracking the mouse position."""
self.iren.untrack_mouse_position()
@wraps(RenderWindowInteractor.track_click_position)
def track_click_position(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.track_click_position."""
self.iren.track_click_position(*args, **kwargs)
@wraps(RenderWindowInteractor.untrack_click_position)
def untrack_click_position(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Stop tracking the click position."""
self.iren.untrack_click_position(*args, **kwargs)
@property
def pickable_actors(self): # numpydoc ignore=RT01
"""Return or set the pickable actors.
When setting, this will be the list of actors to make
pickable. All actors not in the list will be made unpickable.
If ``actors`` is ``None``, all actors will be made unpickable.
Returns
-------
list[pyvista.Actor]
List of actors.
Examples
--------
Add two actors to a :class:`pyvista.Plotter`, make one
pickable, and then list the pickable actors.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> sphere_actor = pl.add_mesh(pv.Sphere())
>>> cube_actor = pl.add_mesh(
... pv.Cube(), pickable=False, style='wireframe'
... )
>>> len(pl.pickable_actors)
1
Set the pickable actors to both actors.
>>> pl.pickable_actors = [sphere_actor, cube_actor]
>>> len(pl.pickable_actors)
2
Set the pickable actors to ``None``.
>>> pl.pickable_actors = None
>>> len(pl.pickable_actors)
0
"""
return [
actor
for renderer in self.renderers
for actor in renderer.actors.values()
if actor.GetPickable()
]
@pickable_actors.setter
def pickable_actors(self, actors=None): # numpydoc ignore=GL08
actors = [] if actors is None else actors
if isinstance(actors, _vtk.vtkActor):
actors = [actors]
if not all(isinstance(actor, _vtk.vtkActor) for actor in actors):
raise TypeError(
f'Expected a vtkActor instance or a list of vtkActors, got '
f'{[type(actor) for actor in actors]} instead.',
)
for renderer in self.renderers:
for actor in renderer.actors.values():
actor.SetPickable(actor in actors)
def _prep_for_close(self):
"""Make sure a screenshot is acquired before closing.
This doesn't actually close anything. It just preps the plotter for
closing.
"""
# Grab screenshot right before renderer closes
self.last_image = self.screenshot(True, return_img=True)
self.last_image_depth = self.get_image_depth()
def increment_point_size_and_line_width(self, increment):
"""Increment point size and line width of all actors.
For every actor in the scene, increment both its point size
and line width by the given value.
Parameters
----------
increment : float
Amount to increment point size and line width.
"""
for renderer in self.renderers:
for actor in renderer._actors.values():
if hasattr(actor, "GetProperty"):
prop = actor.GetProperty()
if hasattr(prop, "SetPointSize"):
prop.SetPointSize(prop.GetPointSize() + increment)
if hasattr(prop, "SetLineWidth"):
prop.SetLineWidth(prop.GetLineWidth() + increment)
self.render()
def zoom_camera(self, value):
"""Zoom of the camera and render.
Parameters
----------
value : float or str
Zoom of the camera. If a float, must be greater than 0. Otherwise,
if a string, must be ``"tight"``. If tight, the plot will be zoomed
such that the actors fill the entire viewport.
"""
self.camera.zoom(value)
self.render()
def reset_key_events(self):
"""Reset all of the key press events to their defaults."""
if not hasattr(self, 'iren'):
return
self.iren.clear_key_event_callbacks()
self.add_key_event('q', self._prep_for_close) # Add no matter what
b_left_down_callback = lambda: self.iren.add_observer(
'LeftButtonPressEvent',
self.left_button_down,
)
self.add_key_event('b', b_left_down_callback)
self.add_key_event('v', lambda: self.isometric_view_interactive())
self.add_key_event('C', lambda: self.enable_cell_picking())
self.add_key_event('Up', lambda: self.zoom_camera(1.05))
self.add_key_event('Down', lambda: self.zoom_camera(0.95))
self.add_key_event('plus', lambda: self.increment_point_size_and_line_width(1))
self.add_key_event('minus', lambda: self.increment_point_size_and_line_width(-1))
@wraps(RenderWindowInteractor.key_press_event)
def key_press_event(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.key_press_event."""
self.iren.key_press_event(*args, **kwargs)
def left_button_down(self, *args):
"""Register the event for a left button down click."""
if hasattr(self.render_window, 'GetOffScreenFramebuffer'):
if not self.render_window.GetOffScreenFramebuffer().GetFBOIndex():
# must raise a runtime error as this causes a segfault on VTK9
raise ValueError('Invoking helper with no framebuffer')
# Get 2D click location on window
click_pos = self.iren.get_event_position()
# Get corresponding click location in the 3D plot
picker = _vtk.vtkWorldPointPicker()
picker.Pick(click_pos[0], click_pos[1], 0, self.renderer)
self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
if np.any(np.isnan(self.pickpoint)):
self.pickpoint[:] = 0
@wraps(RenderWindowInteractor.enable_trackball_style)
def enable_trackball_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_trackball_style."""
self.iren.enable_trackball_style()
@wraps(RenderWindowInteractor.enable_custom_trackball_style)
def enable_custom_trackball_style(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_custom_trackball_style."""
self.iren.enable_custom_trackball_style(*args, **kwargs)
@wraps(RenderWindowInteractor.enable_trackball_actor_style)
def enable_trackball_actor_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_trackball_actor_style."""
self.iren.enable_trackball_actor_style()
@wraps(RenderWindowInteractor.enable_image_style)
def enable_image_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_image_style."""
self.iren.enable_image_style()
@wraps(RenderWindowInteractor.enable_joystick_style)
def enable_joystick_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_joystick_style."""
self.iren.enable_joystick_style()
@wraps(RenderWindowInteractor.enable_joystick_actor_style)
def enable_joystick_actor_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_joystick_actor_style."""
self.iren.enable_joystick_actor_style()
@wraps(RenderWindowInteractor.enable_zoom_style)
def enable_zoom_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_zoom_style."""
self.iren.enable_zoom_style()
@wraps(RenderWindowInteractor.enable_terrain_style)
def enable_terrain_style(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_terrain_style."""
self.iren.enable_terrain_style(*args, **kwargs)
@wraps(RenderWindowInteractor.enable_rubber_band_style)
def enable_rubber_band_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_rubber_band_style."""
self.iren.enable_rubber_band_style()
@wraps(RenderWindowInteractor.enable_rubber_band_2d_style)
def enable_rubber_band_2d_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_rubber_band_2d_style."""
self.iren.enable_rubber_band_2d_style()
@wraps(RenderWindowInteractor.enable_2d_style)
def enable_2d_style(self): # numpydoc ignore=PR01,RT01
"""Wrap RenderWindowInteractor.enable_2d_style."""
self.iren.enable_2d_style()
def enable_stereo_render(self):
"""Enable anaglyph stereo rendering.
Disable this with :func:`disable_stereo_render
<Plotter.disable_stereo_render>`
Examples
--------
Enable stereo rendering to show a cube as an anaglyph image.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.enable_stereo_render()
>>> pl.show()
"""
if self.render_window is not None:
self.render_window.SetStereoTypeToAnaglyph()
self.render_window.StereoRenderOn()
def disable_stereo_render(self):
"""Disable anaglyph stereo rendering.
Enable again with :func:`enable_stereo_render
<Plotter.enable_stereo_render>`
Examples
--------
Enable and then disable stereo rendering. It should show a simple cube.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.enable_stereo_render()
>>> pl.disable_stereo_render()
>>> pl.show()
"""
if self.render_window is not None:
self.render_window.StereoRenderOff()
def hide_axes_all(self):
"""Hide the axes orientation widget in all renderers."""
for renderer in self.renderers:
renderer.hide_axes()
def show_axes_all(self):
"""Show the axes orientation widget in all renderers.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>>
>>> mesh = examples.load_globe()
>>> texture = examples.load_globe_texture()
>>>
>>> # create multi-window plot (1 row, 2 columns)
>>> pl = pv.Plotter(shape=(1, 2))
>>>
>>> # activate subplot 1 and add a mesh
>>> pl.subplot(0, 0)
>>> _ = pl.add_mesh(mesh, texture=texture)
>>>
>>> # activate subplot 2 and add a mesh
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(examples.load_airplane())
>>>
>>> # show the axes orientation widget in all subplots
>>> pl.show_axes_all()
>>>
>>> # display the window
>>> pl.show()
"""
for renderer in self.renderers:
renderer.show_axes()
def isometric_view_interactive(self):
"""Set the current interactive render window to isometric view."""
interactor = self.iren.get_interactor_style()
renderer = interactor.GetCurrentRenderer()
if renderer is None:
renderer = self.renderer
renderer.view_isometric()
def update(self, stime=1, force_redraw=True):
"""Update window, redraw, process messages query.
Parameters
----------
stime : int, default: 1
Duration of timer that interrupt vtkRenderWindowInteractor
in milliseconds.
force_redraw : bool, default: True
Call ``render`` immediately.
"""
if stime <= 0:
stime = 1
curr_time = time.time()
if Plotter.last_update_time > curr_time:
Plotter.last_update_time = curr_time
if self.iren is not None:
update_rate = self.iren.get_desired_update_rate()
if (curr_time - Plotter.last_update_time) > (1.0 / update_rate):
# Allow interaction for a brief moment during interactive updating
# Use the non-blocking ProcessEvents method.
self.iren.process_events()
# Rerender
self.render()
Plotter.last_update_time = curr_time
return
if force_redraw:
self.render()
def add_composite(
self,
dataset,
color=None,
style=None,
scalars=None,
clim=None,
show_edges=None,
edge_color=None,
point_size=None,
line_width=None,
opacity=1.0,
flip_scalars=False,
lighting=None,
n_colors=256,
interpolate_before_map=True,
cmap=None,
label=None,
reset_camera=None,
scalar_bar_args=None,
show_scalar_bar=None,
multi_colors=False,
name=None,
render_points_as_spheres=None,
render_lines_as_tubes=None,
smooth_shading=None,
split_sharp_edges=None,
ambient=None,
diffuse=None,
specular=None,
specular_power=None,
nan_color=None,
nan_opacity=1.0,
culling=None,
rgb=None,
below_color=None,
above_color=None,
annotations=None,
pickable=True,
preference="point",
log_scale=False,
pbr=None,
metallic=None,
roughness=None,
render=True,
component=None,
color_missing_with_nan=False,
copy_mesh=False,
show_vertices=None,
edge_opacity=None,
**kwargs,
):
"""Add a composite dataset to the plotter.
Parameters
----------
dataset : pyvista.MultiBlock
A :class:`pyvista.MultiBlock` dataset.
color : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.color`
Use to make the entire mesh have a single solid color.
Either a string, RGB list, or hex color string. For example:
``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
``color='#FFFFFF'``. Color will be overridden if scalars are
specified. To color each element of the composite dataset
individually, you will need to iteratively call ``add_mesh`` for
each sub-dataset.
style : str, default: 'wireframe'
Visualization style of the mesh. One of the following:
``style='surface'``, ``style='wireframe'``, ``style='points'``.
Defaults to ``'surface'``. Note that ``'wireframe'`` only shows a
wireframe of the outer geometry.
scalars : str, optional
Scalars used to "color" the points or cells of the dataset.
Accepts only a string name of an array that is present on the
composite dataset.
clim : sequence[float], optional
Two item color bar range for scalars. Defaults to minimum and
maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is
also an accepted alias for this.
show_edges : bool, default: :attr:`pyvista.global_theme.show_edges <pyvista.plotting.themes.Theme.show_edges>`
Shows the edges of a mesh. Does not apply to a wireframe
representation.
edge_color : ColorLike, default: :attr:`pyvista.global_theme.edge_color <pyvista.plotting.themes.Theme.edge_color>`
The solid color to give the edges when ``show_edges=True``.
Either a string, RGB list, or hex color string.
Defaults to :attr:`pyvista.global_theme.edge_color
<pyvista.plotting.themes.Theme.edge_color>`.
point_size : float, default: 5.0
Point size of any points in the dataset plotted. Also
applicable when style='points'. Default ``5.0``.
line_width : float, optional
Thickness of lines. Only valid for wireframe and surface
representations.
opacity : float, default: 1.0
Opacity of the mesh. A single float value that will be applied
globally opacity of the mesh and uniformly
applied everywhere - should be between 0 and 1.
flip_scalars : bool, default: False
Flip direction of cmap. Most colormaps allow ``*_r``
suffix to do this as well.
lighting : bool, default: True
Enable or disable view direction lighting.
n_colors : int, default: 256
Number of colors to use when displaying scalars. The scalar bar
will also have this many colors.
interpolate_before_map : bool, default: True
Enabling makes for a smoother scalars display. When ``False``,
OpenGL will interpolate the mapped colors which can result in
showing colors that are not present in the color map.
cmap : str | list, | pyvista.LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
If a string, this is the name of the ``matplotlib`` colormap to use
when mapping the ``scalars``. See available Matplotlib colormaps.
Only applicable for when displaying ``scalars``.
``colormap`` is also an accepted alias
for this. If ``colorcet`` or ``cmocean`` are installed, their
colormaps can be specified by name.
You can also specify a list of colors to override an existing
colormap with a custom one. For example, to create a three color
colormap you might specify ``['green', 'red', 'blue']``.
This parameter also accepts a :class:`pyvista.LookupTable`. If this
is set, all parameters controlling the color map like ``n_colors``
will be ignored.
label : str, optional
String label to use when adding a legend to the scene with
:func:`pyvista.Plotter.add_legend`.
reset_camera : bool, optional
Reset the camera after adding this mesh to the scene. The default
setting is ``None``, where the camera is only reset if this plotter
has already been shown. If ``False``, the camera is not reset
regardless of the state of the ``Plotter``. When ``True``, the
camera is always reset.
scalar_bar_args : dict, optional
Dictionary of keyword arguments to pass when adding the
scalar bar to the scene. For options, see
:func:`pyvista.Plotter.add_scalar_bar`.
show_scalar_bar : bool
If ``False``, a scalar bar will not be added to the
scene. Defaults to ``True`` unless ``rgba=True``.
multi_colors : bool | str | cycler.Cycler | sequence[ColorLike], default: False
Color each block by a solid color using a custom cycler.
If ``True``, the default 'matplotlib' color cycler is used.
See :func:`set_color_cycler<Plotter.set_color_cycler>` for usage of
custom color cyclers.
name : str, optional
The name for the added mesh/actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
render_points_as_spheres : bool, default: False
Render points as spheres rather than dots.
render_lines_as_tubes : bool, default: False
Show lines as thick tubes rather than flat lines. Control
the width with ``line_width``.
smooth_shading : bool, default: :attr`pyvista.plotting.themes.Theme.smooth_shading`
Enable smooth shading when ``True`` using the Phong shading
algorithm. When ``False``, uses flat shading. Automatically
enabled when ``pbr=True``. See :ref:`shading_example`.
split_sharp_edges : bool, default: False
Split sharp edges exceeding 30 degrees when plotting with smooth
shading. Control the angle with the optional keyword argument
``feature_angle``. By default this is ``False`` unless overridden
by the global or plotter theme. Note that enabling this will
create a copy of the input mesh within the plotter. See
:ref:`shading_example`.
ambient : float, default: 0.0
When lighting is enabled, this is the amount of light in
the range of 0 to 1 (default 0.0) that reaches the actor
when not directed at the light source emitted from the
viewer.
diffuse : float, default: 1.0
The diffuse lighting coefficient.
specular : float, default: 0.0
The specular lighting coefficient.
specular_power : float, default: 1.0
The specular power. Between 0.0 and 128.0.
nan_color : ColorLike, default: :attr:`pyvista.plotting.themes.Theme.nan_color`
The color to use for all ``NaN`` values in the plotted
scalar array.
nan_opacity : float, default: 1.0
Opacity of ``NaN`` values. Should be between 0 and 1.
culling : str, bool, default: False
Does not render faces that are culled. This can be helpful for
dense surface meshes, especially when edges are visible, but can
cause flat meshes to be partially displayed. One of the following:
* ``True`` - Enable backface culling
* ``"b"`` - Enable backface culling
* ``"back"`` - Enable backface culling
* ``"backface"`` - Enable backface culling
* ``"f"`` - Enable frontface culling
* ``"front"`` - Enable frontface culling
* ``"frontface"`` - Enable frontface culling
* ``False`` - Disable both backface and frontface culling
rgb : bool, default: False
If an 2 dimensional array is passed as the scalars, plot
those values as RGB(A) colors. ``rgba`` is also an
accepted alias for this. Opacity (the A) is optional. If
a scalars array ending with ``"_rgb"`` or ``"_rgba"`` is passed,
the default becomes ``True``. This can be overridden by setting
this parameter to ``False``.
below_color : ColorLike, optional
Solid color for values below the scalars range
(``clim``). This will automatically set the scalar bar
``below_label`` to ``'below'``.
above_color : ColorLike, optional
Solid color for values below the scalars range
(``clim``). This will automatically set the scalar bar
``above_label`` to ``'above'``.
annotations : dict, optional
Pass a dictionary of annotations. Keys are the float
values in the scalars range to annotate on the scalar bar
and the values are the string annotations.
pickable : bool, default: True
Set whether this actor is pickable.
preference : str, default: 'point'
For each block, when ``block.n_points == block.n_cells`` and
setting scalars, this parameter sets how the scalars will be mapped
to the mesh. For example, when ``'point'`` the scalars will be
associated with the mesh points if available. Can be either
``'point'`` or ``'cell'``.
log_scale : bool, default: False
Use log scale when mapping data to colors. Scalars less
than zero are mapped to the smallest representable
positive float.
pbr : bool, default: False
Enable physics based rendering (PBR) if the mesh is
``PolyData``. Use the ``color`` argument to set the base
color.
metallic : float, default: 0.0
Usually this value is either 0 or 1 for a real material
but any value in between is valid. This parameter is only
used by PBR interpolation.
roughness : float, default: 0.5
This value has to be between 0 (glossy) and 1 (rough). A
glossy material has reflections and a high specular
part. This parameter is only used by PBR
interpolation.
render : bool, default: True
Force a render when ``True``.
component : int, optional
Set component of vector valued scalars to plot. Must be
nonnegative, if supplied. If ``None``, the magnitude of
the vector is plotted.
color_missing_with_nan : bool, default: False
Color any missing values with the ``nan_color``. This is useful
when not all blocks of the composite dataset have the specified
``scalars``.
copy_mesh : bool, default: False
If ``True``, a copy of the mesh will be made before adding it to
the plotter. This is useful if e.g. you would like to add the same
mesh to a plotter multiple times and display different
scalars. Setting ``copy_mesh`` to ``False`` is necessary if you
would like to update the mesh after adding it to the plotter and
have these updates rendered, e.g. by changing the active scalars or
through an interactive widget.
show_vertices : bool, optional
When ``style`` is not ``'points'``, render the external surface
vertices. The following optional keyword arguments may be used to
control the style of the vertices:
* ``vertex_color`` - The color of the vertices
* ``vertex_style`` - Change style to ``'points_gaussian'``
* ``vertex_opacity`` - Control the opacity of the vertices
edge_opacity : float, optional
Edge opacity of the mesh. A single float value that will be applied globally
edge opacity of the mesh and uniformly applied everywhere - should be
between 0 and 1.
.. note::
`edge_opacity` uses ``SetEdgeOpacity`` as the underlying method which
requires VTK version 9.3 or higher. If ``SetEdgeOpacity`` is not
available, `edge_opacity` is set to 1.
**kwargs : dict, optional
Optional keyword arguments.
Returns
-------
pyvista.Actor
Actor of the composite dataset.
pyvista.CompositePolyDataMapper
Composite PolyData mapper.
Examples
--------
Add a sphere and a cube as a multiblock dataset to a plotter and then
change the visibility and color of the blocks.
Note index ``1`` and ``2`` are used to access the individual blocks of
the composite dataset. This is because the :class:`pyvista.MultiBlock`
is the root node of the "tree" and is index ``0``. This allows you to
access individual blocks or the entire composite dataset itself in the
case of multiple nested composite datasets.
>>> import pyvista as pv
>>> dataset = pv.MultiBlock(
... [pv.Cube(), pv.Sphere(center=(0, 0, 1))]
... )
>>> pl = pv.Plotter()
>>> actor, mapper = pl.add_composite(dataset)
>>> mapper.block_attr[1].color = 'b'
>>> mapper.block_attr[1].opacity = 0.5
>>> mapper.block_attr[2].color = 'r'
>>> pl.show()
"""
if not isinstance(dataset, _vtk.vtkCompositeDataSet):
raise TypeError(f'Invalid type ({type(dataset)}). Must be a composite dataset.')
# always convert
dataset = dataset.as_polydata_blocks(copy_mesh)
self.mesh = dataset # for legacy behavior
# Parse arguments
(
scalar_bar_args,
split_sharp_edges,
show_scalar_bar,
feature_angle,
render_points_as_spheres,
smooth_shading,
clim,
cmap,
culling,
name,
nan_color,
color,
texture,
rgb,
interpolation,
remove_existing_actor,
vertex_color,
vertex_style,
vertex_opacity,
) = _common_arg_parser(
dataset,
self._theme,
n_colors,
scalar_bar_args,
split_sharp_edges,
show_scalar_bar,
render_points_as_spheres,
smooth_shading,
pbr,
clim,
cmap,
culling,
name,
nan_color,
nan_opacity,
color,
None,
rgb,
style,
**kwargs,
)
if show_vertices is None:
show_vertices = self._theme.show_vertices
# Compute surface normals if using smooth shading
if smooth_shading:
dataset = dataset._compute_normals(
cell_normals=False,
split_vertices=True,
feature_angle=feature_angle,
)
self.mapper = CompositePolyDataMapper(
dataset,
theme=self._theme,
color_missing_with_nan=color_missing_with_nan,
interpolate_before_map=interpolate_before_map,
)
actor, _ = self.add_actor(self.mapper, render=False)
prop = Property(
self._theme,
interpolation=interpolation,
metallic=metallic,
roughness=roughness,
point_size=point_size,
ambient=ambient,
diffuse=diffuse,
specular=specular,
specular_power=specular_power,
show_edges=show_edges,
color=self.renderer.next_color if color is None else color,
style=style,
edge_color=edge_color,
render_points_as_spheres=render_points_as_spheres,
render_lines_as_tubes=render_lines_as_tubes,
lighting=lighting,
line_width=line_width,
opacity=opacity,
culling=culling,
edge_opacity=edge_opacity,
)
actor.SetProperty(prop)
if label is not None:
self._add_legend_label(actor, label, None, prop.color)
# check if there are any consistent active scalars
if color is not None:
self.mapper.scalar_visibility = False
elif multi_colors:
self.mapper.set_unique_colors(multi_colors)
else:
if scalars is None:
point_name, cell_name = dataset._get_consistent_active_scalars()
if point_name and cell_name:
scalars = point_name if preference == "point" else cell_name
else:
scalars = point_name if point_name is not None else cell_name
elif not isinstance(scalars, str):
raise TypeError(
f'`scalars` must be a string for `add_composite`, not ({type(scalars)})',
)
if scalars is not None:
# enable rgb if the scalars name ends with rgb or rgba
if rgb is None and scalars.endswith(('_rgb', '_rgba')):
rgb = True
show_scalar_bar = False
scalar_bar_args = self.mapper.set_scalars(
scalars,
preference,
component,
annotations,
rgb,
scalar_bar_args,
n_colors,
nan_color,
above_color,
below_color,
clim,
cmap,
flip_scalars,
log_scale,
)
else:
self.mapper.scalar_visibility = False
# Only show scalar bar if there are scalars
if show_scalar_bar and scalars is not None:
self.add_scalar_bar(**scalar_bar_args)
# by default reset the camera if the plotting window has been rendered
if reset_camera is None:
reset_camera = not self._first_time and not self.camera_set
# add this immediately prior to adding the actor to ensure vertices
# are rendered
if show_vertices and style not in ['points', 'points_gaussian']:
self.add_composite(
dataset,
style=vertex_style,
point_size=point_size,
color=vertex_color,
render_points_as_spheres=render_points_as_spheres,
name=f'{name}-vertices',
opacity=vertex_opacity,
lighting=lighting,
render=False,
show_vertices=False,
)
self.add_actor(
actor,
reset_camera=reset_camera,
name=name,
pickable=pickable,
render=render,
remove_existing_actor=remove_existing_actor,
)
return actor, self.mapper
def add_mesh(
self,
mesh,
color=None,
style=None,
scalars=None,
clim=None,
show_edges=None,
edge_color=None,
point_size=None,
line_width=None,
opacity=None,
flip_scalars=False,
lighting=None,
n_colors=256,
interpolate_before_map=None,
cmap=None,
label=None,
reset_camera=None,
scalar_bar_args=None,
show_scalar_bar=None,
multi_colors=False,
name=None,
texture=None,
render_points_as_spheres=None,
render_lines_as_tubes=None,
smooth_shading=None,
split_sharp_edges=None,
ambient=None,
diffuse=None,
specular=None,
specular_power=None,
nan_color=None,
nan_opacity=1.0,
culling=None,
rgb=None,
categories=False,
silhouette=None,
use_transparency=False,
below_color=None,
above_color=None,
annotations=None,
pickable=True,
preference="point",
log_scale=False,
pbr=None,
metallic=None,
roughness=None,
render=True,
user_matrix=None,
component=None,
emissive=None,
copy_mesh=False,
backface_params=None,
show_vertices=None,
edge_opacity=None,
**kwargs,
):
"""Add any PyVista/VTK mesh or dataset that PyVista can wrap to the scene.
This method is using a mesh representation to view the surfaces
and/or geometry of datasets. For volume rendering, see
:func:`pyvista.Plotter.add_volume`.
To see the what most of the following parameters look like in action,
please refer to :class:`pyvista.Property`.
Parameters
----------
mesh : pyvista.DataSet or pyvista.MultiBlock or vtk.vtkAlgorithm
Any PyVista or VTK mesh is supported. Also, any dataset
that :func:`pyvista.wrap` can handle including NumPy
arrays of XYZ points. Plotting also supports VTK algorithm
objects (``vtk.vtkAlgorithm`` and ``vtk.vtkAlgorithmOutput``).
When passing an algorithm, the rendering pipeline will be
connected to the passed algorithm to dynamically update
the scene.
color : ColorLike, optional
Use to make the entire mesh have a single solid color.
Either a string, RGB list, or hex color string. For example:
``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
``color='#FFFFFF'``. Color will be overridden if scalars are
specified.
Defaults to :attr:`pyvista.global_theme.color
<pyvista.plotting.themes.Theme.color>`.
style : str, optional
Visualization style of the mesh. One of the following:
``style='surface'``, ``style='wireframe'``, ``style='points'``,
``style='points_gaussian'``. Defaults to ``'surface'``. Note that
``'wireframe'`` only shows a wireframe of the outer geometry.
``'points_gaussian'`` can be modified with the ``emissive``,
``render_points_as_spheres`` options.
scalars : str | numpy.ndarray, optional
Scalars used to "color" the mesh. Accepts a string name
of an array that is present on the mesh or an array equal
to the number of cells or the number of points in the
mesh. Array should be sized as a single vector. If both
``color`` and ``scalars`` are ``None``, then the active
scalars are used.
clim : sequence[float], optional
Two item color bar range for scalars. Defaults to minimum and
maximum of scalars array. Example: ``[-1, 2]``. ``rng`` is
also an accepted alias for this.
show_edges : bool, optional
Shows the edges of a mesh. Does not apply to a wireframe
representation.
edge_color : ColorLike, optional
The solid color to give the edges when ``show_edges=True``.
Either a string, RGB list, or hex color string.
Defaults to :attr:`pyvista.global_theme.edge_color
<pyvista.plotting.themes.Theme.edge_color>`.
point_size : float, optional
Point size of any nodes in the dataset plotted. Also
applicable when style='points'. Default ``5.0``.
line_width : float, optional
Thickness of lines. Only valid for wireframe and surface
representations. Default ``None``.
opacity : float | str| array_like
Opacity of the mesh. If a single float value is given, it
will be the global opacity of the mesh and uniformly
applied everywhere - should be between 0 and 1. A string
can also be specified to map the scalars range to a
predefined opacity transfer function (options include:
``'linear'``, ``'linear_r'``, ``'geom'``, ``'geom_r'``).
A string could also be used to map a scalars array from
the mesh to the opacity (must have same number of elements
as the ``scalars`` argument). Or you can pass a custom
made transfer function that is an array either
``n_colors`` in length or shorter.
flip_scalars : bool, default: False
Flip direction of cmap. Most colormaps allow ``*_r``
suffix to do this as well.
lighting : bool, optional
Enable or disable view direction lighting. Default ``False``.
n_colors : int, optional
Number of colors to use when displaying scalars. Defaults to 256.
The scalar bar will also have this many colors.
interpolate_before_map : bool, optional
Enabling makes for a smoother scalars display. Default is
``True``. When ``False``, OpenGL will interpolate the
mapped colors which can result is showing colors that are
not present in the color map.
cmap : str | list | pyvista.LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
If a string, this is the name of the ``matplotlib`` colormap to use
when mapping the ``scalars``. See available Matplotlib colormaps.
Only applicable for when displaying ``scalars``.
``colormap`` is also an accepted alias
for this. If ``colorcet`` or ``cmocean`` are installed, their
colormaps can be specified by name.
You can also specify a list of colors to override an existing
colormap with a custom one. For example, to create a three color
colormap you might specify ``['green', 'red', 'blue']``.
This parameter also accepts a :class:`pyvista.LookupTable`. If this
is set, all parameters controlling the color map like ``n_colors``
will be ignored.
label : str, optional
String label to use when adding a legend to the scene with
:func:`pyvista.Plotter.add_legend`.
reset_camera : bool, optional
Reset the camera after adding this mesh to the scene. The default
setting is ``None``, where the camera is only reset if this plotter
has already been shown. If ``False``, the camera is not reset
regardless of the state of the ``Plotter``. When ``True``, the
camera is always reset.
scalar_bar_args : dict, optional
Dictionary of keyword arguments to pass when adding the
scalar bar to the scene. For options, see
:func:`pyvista.Plotter.add_scalar_bar`.
show_scalar_bar : bool, optional
If ``False``, a scalar bar will not be added to the
scene.
multi_colors : bool | str | cycler.Cycler | sequence[ColorLike], default: False
If a :class:`pyvista.MultiBlock` dataset is given this will color
each block by a solid color using a custom cycler.
If ``True``, the default 'matplotlib' color cycler is used.
See :func:`set_color_cycler<Plotter.set_color_cycler>` for usage of
custom color cycles.
name : str, optional
The name for the added mesh/actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
texture : pyvista.Texture or np.ndarray, optional
A texture to apply if the input mesh has texture
coordinates. This will not work with MultiBlock
datasets.
render_points_as_spheres : bool, optional
Render points as spheres rather than dots.
render_lines_as_tubes : bool, optional
Show lines as thick tubes rather than flat lines. Control
the width with ``line_width``.
smooth_shading : bool, optional
Enable smooth shading when ``True`` using the Phong
shading algorithm. When ``False``, use flat shading.
Automatically enabled when ``pbr=True``. See
:ref:`shading_example`.
split_sharp_edges : bool, optional
Split sharp edges exceeding 30 degrees when plotting with smooth
shading. Control the angle with the optional keyword argument
``feature_angle``. By default this is ``False`` unless overridden
by the global or plotter theme. Note that enabling this will
create a copy of the input mesh within the plotter. See
:ref:`shading_example`.
ambient : float, optional
When lighting is enabled, this is the amount of light in
the range of 0 to 1 (default 0.0) that reaches the actor
when not directed at the light source emitted from the
viewer.
diffuse : float, optional
The diffuse lighting coefficient. Default 1.0.
specular : float, optional
The specular lighting coefficient. Default 0.0.
specular_power : float, optional
The specular power. Between 0.0 and 128.0.
nan_color : ColorLike, optional
The color to use for all ``NaN`` values in the plotted
scalar array.
nan_opacity : float, optional
Opacity of ``NaN`` values. Should be between 0 and 1.
Default 1.0.
culling : str, optional
Does not render faces that are culled. Options are
``'front'`` or ``'back'``. This can be helpful for dense
surface meshes, especially when edges are visible, but can
cause flat meshes to be partially displayed. Defaults to
``False``.
rgb : bool, optional
If an 2 dimensional array is passed as the scalars, plot
those values as RGB(A) colors. ``rgba`` is also an
accepted alias for this. Opacity (the A) is optional. If
a scalars array ending with ``"_rgba"`` is passed, the default
becomes ``True``. This can be overridden by setting this
parameter to ``False``.
categories : bool, optional
If set to ``True``, then the number of unique values in
the scalar array will be used as the ``n_colors``
argument.
silhouette : dict, bool, optional
If set to ``True``, plot a silhouette highlight for the
mesh. This feature is only available for a triangulated
``PolyData``. As a ``dict``, it contains the properties
of the silhouette to display:
* ``color``: ``ColorLike``, color of the silhouette
* ``line_width``: ``float``, edge width
* ``opacity``: ``float`` between 0 and 1, edge transparency
* ``feature_angle``: If a ``float``, display sharp edges
exceeding that angle in degrees.
* ``decimate``: ``float`` between 0 and 1, level of decimation
use_transparency : bool, optional
Invert the opacity mappings and make the values correspond
to transparency.
below_color : ColorLike, optional
Solid color for values below the scalars range
(``clim``). This will automatically set the scalar bar
``below_label`` to ``'below'``.
above_color : ColorLike, optional
Solid color for values below the scalars range
(``clim``). This will automatically set the scalar bar
``above_label`` to ``'above'``.
annotations : dict, optional
Pass a dictionary of annotations. Keys are the float
values in the scalars range to annotate on the scalar bar
and the values are the string annotations.
pickable : bool, optional
Set whether this actor is pickable.
preference : str, default: "point"
When ``mesh.n_points == mesh.n_cells`` and setting
scalars, this parameter sets how the scalars will be
mapped to the mesh. Default ``'point'``, causes the
scalars will be associated with the mesh points. Can be
either ``'point'`` or ``'cell'``.
log_scale : bool, default: False
Use log scale when mapping data to colors. Scalars less
than zero are mapped to the smallest representable
positive float.
pbr : bool, optional
Enable physics based rendering (PBR) if the mesh is
``PolyData``. Use the ``color`` argument to set the base
color.
metallic : float, optional
Usually this value is either 0 or 1 for a real material
but any value in between is valid. This parameter is only
used by PBR interpolation.
roughness : float, optional
This value has to be between 0 (glossy) and 1 (rough). A
glossy material has reflections and a high specular
part. This parameter is only used by PBR
interpolation.
render : bool, default: True
Force a render when ``True``.
user_matrix : np.ndarray | vtk.vtkMatrix4x4, default: np.eye(4)
Matrix passed to the Actor class before rendering. This affects the
actor/rendering only, not the input volume itself. The user matrix is the
last transformation applied to the actor before rendering. Defaults to the
identity matrix.
component : int, optional
Set component of vector valued scalars to plot. Must be
nonnegative, if supplied. If ``None``, the magnitude of
the vector is plotted.
emissive : bool, optional
Treat the points/splats as emissive light sources. Only valid for
``style='points_gaussian'`` representation.
copy_mesh : bool, default: False
If ``True``, a copy of the mesh will be made before adding it to
the plotter. This is useful if you would like to add the same
mesh to a plotter multiple times and display different
scalars. Setting ``copy_mesh`` to ``False`` is necessary if you
would like to update the mesh after adding it to the plotter and
have these updates rendered, e.g. by changing the active scalars or
through an interactive widget. This should only be set to ``True``
with caution. Defaults to ``False``. This is ignored if the input
is a ``vtkAlgorithm`` subclass.
backface_params : dict | pyvista.Property, optional
A :class:`pyvista.Property` or a dict of parameters to use for
backface rendering. This is useful for instance when the inside of
oriented surfaces has a different color than the outside. When a
:class:`pyvista.Property`, this is directly used for backface
rendering. When a dict, valid keys are :class:`pyvista.Property`
attributes, and values are corresponding values to use for the
given property. Omitted keys (or the default of
``backface_params=None``) default to the corresponding frontface
properties.
show_vertices : bool, optional
When ``style`` is not ``'points'``, render the external surface
vertices. The following optional keyword arguments may be used to
control the style of the vertices:
* ``vertex_color`` - The color of the vertices
* ``vertex_style`` - Change style to ``'points_gaussian'``
* ``vertex_opacity`` - Control the opacity of the vertices
edge_opacity : float, optional
Edge opacity of the mesh. A single float value that will be applied globally
edge opacity of the mesh and uniformly applied everywhere - should be
between 0 and 1.
.. note::
`edge_opacity` uses ``SetEdgeOpacity`` as the underlying method which
requires VTK version 9.3 or higher. If ``SetEdgeOpacity`` is not
available, `edge_opacity` is set to 1.
**kwargs : dict, optional
Optional keyword arguments.
Returns
-------
pyvista.plotting.actor.Actor
Actor of the mesh.
Examples
--------
Add a sphere to the plotter and show it with a custom scalar
bar title.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere['Data'] = sphere.points[:, 2]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
... sphere, scalar_bar_args={'title': 'Z Position'}
... )
>>> plotter.show()
Plot using RGB on a single cell. Note that since the number of
points and the number of cells are identical, we have to pass
``preference='cell'``.
>>> import pyvista as pv
>>> import numpy as np
>>> vertices = np.array(
... [
... [0, 0, 0],
... [1, 0, 0],
... [0.5, 0.667, 0],
... [0.5, 0.33, 0.667],
... ]
... )
>>> faces = np.hstack(
... [[3, 0, 1, 2], [3, 0, 3, 2], [3, 0, 1, 3], [3, 1, 2, 3]]
... )
>>> mesh = pv.PolyData(vertices, faces)
>>> mesh.cell_data['colors'] = [
... [255, 255, 255],
... [0, 255, 0],
... [0, 0, 255],
... [255, 0, 0],
... ]
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
... mesh,
... scalars='colors',
... lighting=False,
... rgb=True,
... preference='cell',
... )
>>> plotter.camera_position = 'xy'
>>> plotter.show()
Note how this varies from ``preference=='point'``. This is
because each point is now being individually colored, versus
in ``preference=='point'``, each cell face is individually
colored.
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
... mesh,
... scalars='colors',
... lighting=False,
... rgb=True,
... preference='point',
... )
>>> plotter.camera_position = 'xy'
>>> plotter.show()
Plot a plane with a constant color and vary its opacity by point.
>>> plane = pv.Plane()
>>> plane.plot(
... color='b',
... opacity=np.linspace(0, 1, plane.n_points),
... show_edges=True,
... )
Plot the points of a sphere with Gaussian smoothing while coloring by z
position.
>>> mesh = pv.Sphere()
>>> mesh.plot(
... scalars=mesh.points[:, 2],
... style='points_gaussian',
... opacity=0.5,
... point_size=10,
... render_points_as_spheres=False,
... show_scalar_bar=False,
... )
Plot spheres using `points_gaussian` style and scale them by radius.
>>> N_SPHERES = 1_000_000
>>> rng = np.random.default_rng(seed=0)
>>> pos = rng.random((N_SPHERES, 3))
>>> rad = rng.random(N_SPHERES) * 0.01
>>> pdata = pv.PolyData(pos)
>>> pdata['radius'] = rad
>>> pdata.plot(
... style='points_gaussian',
... emissive=False,
... render_points_as_spheres=True,
... )
"""
if user_matrix is None:
user_matrix = np.eye(4)
if style == 'points_gaussian':
self.mapper = PointGaussianMapper(theme=self.theme, emissive=emissive)
else:
self.mapper = DataSetMapper(theme=self.theme)
if render_lines_as_tubes and show_edges:
warnings.warn(
'`show_edges=True` not supported when `render_lines_as_tubes=True`. Ignoring `show_edges`.',
UserWarning,
)
show_edges = False
mesh, algo = algorithm_to_mesh_handler(mesh)
# Convert the VTK data object to a pyvista wrapped object if necessary
if not is_pyvista_dataset(mesh):
mesh = wrap(mesh)
if not is_pyvista_dataset(mesh):
raise TypeError(
f'Object type ({type(mesh)}) not supported for plotting in PyVista.',
)
if isinstance(mesh, pyvista.PointSet):
# cast to PointSet to PolyData
if algo is not None:
algo = pointset_to_polydata_algorithm(algo)
mesh, algo = algorithm_to_mesh_handler(algo)
else:
mesh = mesh.cast_to_polydata(deep=False)
elif isinstance(mesh, pyvista.MultiBlock):
if algo is not None:
raise TypeError(
'Algorithms with `MultiBlock` output type are not supported by `add_mesh` at this time.',
)
actor, _ = self.add_composite(
mesh,
color=color,
style=style,
scalars=scalars,
clim=clim,
show_edges=show_edges,
edge_color=edge_color,
point_size=point_size,
line_width=line_width,
opacity=opacity,
flip_scalars=flip_scalars,
lighting=lighting,
n_colors=n_colors,
interpolate_before_map=interpolate_before_map,
cmap=cmap,
label=label,
reset_camera=reset_camera,
scalar_bar_args=scalar_bar_args,
show_scalar_bar=show_scalar_bar,
multi_colors=multi_colors,
name=name,
render_points_as_spheres=render_points_as_spheres,
render_lines_as_tubes=render_lines_as_tubes,
smooth_shading=smooth_shading,
split_sharp_edges=split_sharp_edges,
ambient=ambient,
diffuse=diffuse,
specular=specular,
specular_power=specular_power,
nan_color=nan_color,
nan_opacity=nan_opacity,
culling=culling,
rgb=rgb,
below_color=below_color,
above_color=above_color,
pickable=pickable,
preference=preference,
log_scale=log_scale,
pbr=pbr,
metallic=metallic,
roughness=roughness,
render=render,
show_vertices=show_vertices,
edge_opacity=edge_opacity,
**kwargs,
)
return actor
elif copy_mesh and algo is None:
# A shallow copy of `mesh` is made here so when we set (or add) scalars
# active, it doesn't modify the original input mesh.
# We ignore `copy_mesh` if the input is an algorithm
mesh = mesh.copy(deep=False)
# Parse arguments
(
scalar_bar_args,
split_sharp_edges,
show_scalar_bar,
feature_angle,
render_points_as_spheres,
smooth_shading,
clim,
cmap,
culling,
name,
nan_color,
color,
texture,
rgb,
interpolation,
remove_existing_actor,
vertex_color,
vertex_style,
vertex_opacity,
) = _common_arg_parser(
mesh,
self._theme,
n_colors,
scalar_bar_args,
split_sharp_edges,
show_scalar_bar,
render_points_as_spheres,
smooth_shading,
pbr,
clim,
cmap,
culling,
name,
nan_color,
nan_opacity,
color,
texture,
rgb,
style,
**kwargs,
)
if show_vertices is None:
show_vertices = self._theme.show_vertices
if edge_opacity is None and pyvista.vtk_version_info >= (9, 3):
edge_opacity = self._theme.edge_opacity
if silhouette is None:
silhouette = self._theme.silhouette.enabled
if silhouette:
if isinstance(silhouette, dict):
self.add_silhouette(algo or mesh, **silhouette)
else:
self.add_silhouette(algo or mesh)
# Try to plot something if no preference given
if scalars is None and color is None and texture is None:
# Make sure scalars components are not vectors/tuples
scalars = mesh.active_scalars_name
# Don't allow plotting of string arrays by default
if scalars is not None: # and np.issubdtype(mesh.active_scalars.dtype, np.number):
scalar_bar_args.setdefault('title', scalars)
else:
scalars = None
# Make sure scalars is a numpy array after this point
original_scalar_name = None
scalars_name = pyvista.DEFAULT_SCALARS_NAME
if isinstance(scalars, str):
self.mapper.array_name = scalars
# enable rgb if the scalars name ends with rgb or rgba
if rgb is None:
if scalars.endswith(('_rgb', '_rgba')):
rgb = True
original_scalar_name = scalars
scalars = get_array(mesh, scalars, preference=preference, err=True)
scalar_bar_args.setdefault('title', original_scalar_name)
scalars_name = original_scalar_name
# Set the active scalars name here. If the name already exists in
# the input mesh, it may not be set as the active scalars within
# the mapper. This should be refactored by 0.36.0
field = get_array_association(mesh, original_scalar_name, preference=preference)
self.mapper.scalar_map_mode = field.name
# set preference for downstream use with actual
if field == FieldAssociation.POINT:
preference = 'point'
elif field == FieldAssociation.CELL:
preference = 'cell'
if algo is not None:
# Ensures that the right scalars are set as active on
# each pipeline request
algo = active_scalars_algorithm(algo, original_scalar_name, preference=preference)
mesh, algo = algorithm_to_mesh_handler(algo)
else:
# Otherwise, make sure the mesh object's scalars are set
if field == FieldAssociation.POINT:
mesh.point_data.active_scalars_name = original_scalar_name
elif field == FieldAssociation.CELL:
mesh.cell_data.active_scalars_name = original_scalar_name
# Compute surface normals if using smooth shading
if smooth_shading:
if algo is not None:
raise TypeError(
'Smooth shading is not currently supported when a vtkAlgorithm is passed.',
)
mesh, scalars = prepare_smooth_shading(
mesh,
scalars,
texture,
split_sharp_edges,
feature_angle,
preference,
)
if rgb:
show_scalar_bar = False
if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4:
raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.')
if algo is None and not self.theme.allow_empty_mesh and not mesh.n_points:
# Algorithms may initialize with an empty mesh
raise ValueError(
'Empty meshes cannot be plotted. Input mesh has zero points. To allow plotting empty meshes, set `pv.global_theme.allow_empty_mesh = True`',
)
# set main values
self.mesh = mesh
self.mapper.dataset = self.mesh
if interpolate_before_map is not None:
self.mapper.interpolate_before_map = interpolate_before_map
set_algorithm_input(self.mapper, algo or mesh)
actor = Actor(mapper=self.mapper)
actor.user_matrix = user_matrix
if texture is not None:
if isinstance(texture, np.ndarray):
texture = numpy_to_texture(texture)
if not isinstance(texture, (_vtk.vtkTexture, _vtk.vtkOpenGLTexture)):
raise TypeError(f'Invalid texture type ({type(texture)})')
if mesh.GetPointData().GetTCoords() is None:
raise ValueError(
'Input mesh does not have texture coordinates to support the texture.',
)
actor.texture = texture
# Set color to white by default when using a texture
if color is None:
color = 'white'
if scalars is None:
show_scalar_bar = False
self.mapper.scalar_visibility = False
# see https://github.com/pyvista/pyvista/issues/950
mesh.set_active_scalars(None)
# Handle making opacity array
custom_opac, opacity = process_opacity(
mesh,
opacity,
preference,
n_colors,
scalars,
use_transparency,
)
# Scalars formatting ==================================================
if scalars is not None:
self.mapper.set_scalars(
scalars,
scalars_name,
n_colors,
scalar_bar_args,
rgb,
component,
preference,
custom_opac,
annotations,
log_scale,
nan_color,
above_color,
below_color,
cmap,
flip_scalars,
opacity,
categories,
clim,
)
self.mapper.scalar_visibility = True
elif custom_opac: # no scalars but custom opacity
self.mapper.set_custom_opacity(
opacity,
color,
n_colors,
preference,
)
self.mapper.scalar_visibility = True
else:
self.mapper.scalar_visibility = False
# Set actor properties ================================================
prop_kwargs = dict(
theme=self._theme,
interpolation=interpolation,
metallic=metallic,
roughness=roughness,
point_size=point_size,
ambient=ambient,
diffuse=diffuse,
specular=specular,
specular_power=specular_power,
show_edges=show_edges,
color=self.renderer.next_color if color is None else color,
style=style if style != 'points_gaussian' else 'points',
edge_color=edge_color,
render_lines_as_tubes=render_lines_as_tubes,
lighting=lighting,
line_width=line_width,
culling=culling,
edge_opacity=edge_opacity,
)
if isinstance(opacity, (float, int)):
prop_kwargs['opacity'] = opacity
prop = Property(**prop_kwargs)
actor.SetProperty(prop)
if style == 'points_gaussian':
self.mapper.scale_factor = prop.point_size * self.mapper.dataset.length / 1300
if not render_points_as_spheres and not self.mapper.emissive:
if prop.opacity >= 1.0:
prop.opacity = 0.9999 # otherwise, weird triangles
if render_points_as_spheres:
if style == 'points_gaussian':
self.mapper.use_circular_splat(prop.opacity)
prop.opacity = 1.0
else:
prop.render_points_as_spheres = render_points_as_spheres
if backface_params is not None:
if isinstance(backface_params, Property):
backface_prop = backface_params
elif isinstance(backface_params, dict):
# preserve omitted kwargs from frontface
backface_kwargs = deepcopy(prop_kwargs)
backface_kwargs.update(backface_params)
backface_prop = Property(**backface_kwargs)
else:
raise TypeError(
'Backface params must be a pyvista.Property or a dict, '
f'not {type(backface_params).__name__}.',
)
actor.backface_prop = backface_prop
# legend label
if label is not None:
self._add_legend_label(actor, label, scalars, actor.prop.color)
# by default reset the camera if the plotting window has been rendered
if reset_camera is None:
reset_camera = not self._first_time and not self.camera_set
# add this immediately prior to adding the actor to ensure vertices
# are rendered
if show_vertices and style not in ['points', 'points_gaussian']:
self.add_mesh(
extract_surface_algorithm(algo or mesh),
style=vertex_style,
point_size=point_size,
color=vertex_color,
render_points_as_spheres=render_points_as_spheres,
name=f'{name}-vertices',
opacity=vertex_opacity,
lighting=lighting,
render=False,
show_vertices=False,
)
self.add_actor(
actor,
reset_camera=reset_camera,
name=name,
pickable=pickable,
render=render,
remove_existing_actor=remove_existing_actor,
)
# hide scalar bar if using special scalars
if scalar_bar_args.get('title') == '__custom_rgba':
show_scalar_bar = False
# Only show scalar bar if there are scalars
if show_scalar_bar and scalars is not None:
self.add_scalar_bar(**scalar_bar_args)
self.renderer.Modified()
return actor
def _add_legend_label(self, actor, label, scalars, color):
"""Add a legend label based on an actor and its scalars."""
if not isinstance(label, str):
raise TypeError('Label must be a string')
if (
hasattr(self.mesh, '_glyph_geom')
and self.mesh._glyph_geom is not None
and self.mesh._glyph_geom[0] is not None
):
# Using only the first geometry
geom = pyvista.PolyData(self.mesh._glyph_geom[0])
else:
geom = pyvista.Triangle()
if scalars is not None:
geom = pyvista.Box()
geom.points -= geom.center
addr = actor.GetAddressAsString("")
self.renderer._labels[addr] = [geom, label, color]
def add_volume(
self,
volume,
scalars=None,
clim=None,
resolution=None,
opacity='linear',
n_colors=256,
cmap=None,
flip_scalars=False,
reset_camera=None,
name=None,
ambient=None,
categories=False,
culling=False,
multi_colors=False,
blending='composite',
mapper=None,
scalar_bar_args=None,
show_scalar_bar=None,
annotations=None,
pickable=True,
preference="point",
opacity_unit_distance=None,
shade=False,
diffuse=0.7, # TODO: different default for volumes
specular=0.2, # TODO: different default for volumes
specular_power=10.0, # TODO: different default for volumes
render=True,
user_matrix=None,
log_scale=False,
**kwargs,
):
"""Add a volume, rendered using a smart mapper by default.
Requires a 3D data type like :class:`numpy.ndarray`,
:class:`pyvista.ImageData`, :class:`pyvista.RectilinearGrid`,
or :class:`pyvista.UnstructuredGrid`.
Parameters
----------
volume : 3D numpy.ndarray | pyvista.DataSet
The input volume to visualize. 3D numpy arrays are accepted.
.. warning::
If the input is not :class:`numpy.ndarray`,
:class:`pyvista.ImageData`, or :class:`pyvista.RectilinearGrid`,
volume rendering will often have poor performance.
scalars : str | numpy.ndarray, optional
Scalars used to "color" the mesh. Accepts a string name of an
array that is present on the mesh or an array with length equal
to the number of cells or the number of points in the
mesh. If ``scalars`` is ``None``, then the active scalars are used.
Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional,
the scalars will be mapped to the lookup table. If 2 dimensional
the scalars will be directly mapped to RGBA values, array should be
shaped ``(N, 4)`` where ``N`` is the number of points, and of
datatype ``np.uint8``.
Scalars may be 1 dimensional or 2 dimensional. If 1 dimensional,
the scalars will be mapped to the lookup table. If 2 dimensional
the scalars will be directly mapped to RGBA values, array should be
shaped ``(N, 4)`` where ``N`` is the number of points, and of
datatype ``np.uint8``.
clim : sequence[float] | float, optional
Color bar range for scalars. For example: ``[-1, 2]``. Defaults to
minimum and maximum of scalars array if the scalars dtype is not
``np.uint8``. ``rng`` is also an accepted alias for this parameter.
If the scalars datatype is ``np.uint8``, this parameter defaults to
``[0, 256]``.
If a single value is given, the range ``[-clim, clim]`` is used.
resolution : list, optional
Block resolution. For example ``[1, 1, 1]``. Resolution must be
non-negative. While VTK accepts negative spacing, this results in
unexpected behavior. See:
`pyvista #1967 <https://github.com/pyvista/pyvista/issues/1967>`_.
opacity : str | numpy.ndarray, optional
Opacity mapping for the scalars array.
A string can also be specified to map the scalars range to a
predefined opacity transfer function. Or you can pass a custom made
transfer function that is an array either ``n_colors`` in length or
array, or you can pass a string to select a built in transfer
function. If a string, should be one of the following:
* ``'linear'`` - Linear
* ``'linear_r'`` - Linear except reversed
* ``'geom'`` - Evenly spaced on the log scale
* ``'geom_r'`` - Evenly spaced on the log scale except reversed
* ``'sigmoid'`` - Linear map between -10.0 and 10.0
* ``'sigmoid_1'`` - Linear map between -1.0 and 1.0
* ``'sigmoid_2'`` - Linear map between -2.0 and 2.0
* ``'sigmoid_3'`` - Linear map between -3.0 and 3.0
* ``'sigmoid_4'`` - Linear map between -4.0 and 4.0
* ``'sigmoid_5'`` - Linear map between -5.0 and 5.0
* ``'sigmoid_6'`` - Linear map between -6.0 and 6.0
* ``'sigmoid_7'`` - Linear map between -7.0 and 7.0
* ``'sigmoid_8'`` - Linear map between -8.0 and 8.0
* ``'sigmoid_9'`` - Linear map between -9.0 and 9.0
* ``'sigmoid_10'`` - Linear map between -10.0 and 10.0
* ``'sigmoid_15'`` - Linear map between -15.0 and 15.0
* ``'sigmoid_20'`` - Linear map between -20.0 and 20.0
* ``'foreground'`` - Transparent background and opaque foreground.
Intended for use with segmentation labels. Assumes the smallest
scalar value of the array is the background value (e.g. 0).
If RGBA scalars are provided, this parameter is set to ``'linear'``
to ensure the opacity transfer function has no effect on the input
opacity values.
n_colors : int, optional
Number of colors to use when displaying scalars. Defaults to 256.
The scalar bar will also have this many colors.
cmap : str | list | pyvista.LookupTable, default: :attr:`pyvista.plotting.themes.Theme.cmap`
If a string, this is the name of the ``matplotlib`` colormap to use
when mapping the ``scalars``. See available Matplotlib colormaps.
Only applicable for when displaying ``scalars``.
``colormap`` is also an accepted alias
for this. If ``colorcet`` or ``cmocean`` are installed, their
colormaps can be specified by name.
You can also specify a list of colors to override an existing
colormap with a custom one. For example, to create a three color
colormap you might specify ``['green', 'red', 'blue']``.
This parameter also accepts a :class:`pyvista.LookupTable`. If this
is set, all parameters controlling the color map like ``n_colors``
will be ignored.
flip_scalars : bool, optional
Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
this as well.
reset_camera : bool, optional
Reset the camera after adding this mesh to the scene.
name : str, optional
The name for the added actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
ambient : float, optional
When lighting is enabled, this is the amount of light from
0 to 1 that reaches the actor when not directed at the
light source emitted from the viewer. Default 0.0.
categories : bool, optional
If set to ``True``, then the number of unique values in the scalar
array will be used as the ``n_colors`` argument.
culling : str, optional
Does not render faces that are culled. Options are ``'front'`` or
``'back'``. This can be helpful for dense surface meshes,
especially when edges are visible, but can cause flat
meshes to be partially displayed. Defaults ``False``.
multi_colors : bool, optional
Whether or not to use multiple colors when plotting MultiBlock
object. Blocks will be colored sequentially as 'Reds', 'Greens',
'Blues', and 'Grays'.
blending : str, optional
Blending mode for visualisation of the input object(s). Can be
one of 'additive', 'maximum', 'minimum', 'composite', or
'average'. Defaults to 'composite'.
mapper : str, optional
Volume mapper to use given by name. Options include:
``'fixed_point'``, ``'gpu'``, ``'open_gl'``, and
``'smart'``. If ``None`` the ``"volume_mapper"`` in the
``self._theme`` is used. If using ``'fixed_point'``,
only ``ImageData`` types can be used.
.. note::
If a :class:`pyvista.UnstructuredGrid` is input, the 'ugrid'
mapper (``vtkUnstructuredGridVolumeRayCastMapper``) will be
used regardless.
.. note::
The ``'smart'`` mapper chooses one of the other listed
mappers based on rendering parameters and available
hardware. Most of the time the ``'smart'`` simply checks
if a GPU is available and if so, uses the ``'gpu'``
mapper, otherwise using the ``'fixed_point'`` mapper.
.. warning::
The ``'fixed_point'`` mapper is CPU-based and will have
lower performance than the ``'gpu'`` or ``'open_gl'``
mappers.
scalar_bar_args : dict, optional
Dictionary of keyword arguments to pass when adding the
scalar bar to the scene. For options, see
:func:`pyvista.Plotter.add_scalar_bar`.
show_scalar_bar : bool
If ``False``, a scalar bar will not be added to the
scene. Defaults to ``True``.
annotations : dict, optional
Pass a dictionary of annotations. Keys are the float
values in the scalars range to annotate on the scalar bar
and the values are the string annotations.
pickable : bool, optional
Set whether this mesh is pickable.
preference : str, optional
When ``mesh.n_points == mesh.n_cells`` and setting
scalars, this parameter sets how the scalars will be
mapped to the mesh. Default ``'point'``, causes the
scalars will be associated with the mesh points. Can be
either ``'point'`` or ``'cell'``.
opacity_unit_distance : float, optional
Set/Get the unit distance on which the scalar opacity
transfer function is defined. Meaning that over that
distance, a given opacity (from the transfer function) is
accumulated. This is adjusted for the actual sampling
distance during rendering. By default, this is the length
of the diagonal of the bounding box of the volume divided
by the dimensions.
shade : bool, default: False
Default off. If shading is turned on, the mapper may
perform shading calculations - in some cases shading does
not apply (for example, in a maximum intensity projection)
and therefore shading will not be performed even if this
flag is on.
diffuse : float, default: 0.7
The diffuse lighting coefficient.
specular : float, default: 0.2
The specular lighting coefficient.
specular_power : float, default: 10.0
The specular power. Between ``0.0`` and ``128.0``.
render : bool, default: True
Force a render when True.
user_matrix : np.ndarray | vtk.vtkMatrix4x4, default: np.eye(4)
Matrix passed to the Volume class before rendering. This affects the
actor/rendering only, not the input volume itself. The user matrix is the
last transformation applied to the actor before rendering. Defaults to the
identity matrix.
log_scale : bool, default: False
Use log scale when mapping data to colors. Scalars less
than zero are mapped to the smallest representable
positive float.
**kwargs : dict, optional
Optional keyword arguments.
Returns
-------
pyvista.Actor
Actor of the volume.
Examples
--------
Show a built-in volume example with the coolwarm colormap.
>>> from pyvista import examples
>>> import pyvista as pv
>>> bolt_nut = examples.download_bolt_nut()
>>> pl = pv.Plotter()
>>> _ = pl.add_volume(bolt_nut, cmap="coolwarm")
>>> pl.show()
Create a volume from scratch and plot it using single vector of
scalars.
>>> import pyvista as pv
>>> grid = pv.ImageData(dimensions=(9, 9, 9))
>>> grid['scalars'] = -grid.x
>>> pl = pv.Plotter()
>>> _ = pl.add_volume(grid, opacity='linear')
>>> pl.show()
Plot a volume from scratch using RGBA scalars
>>> import pyvista as pv
>>> import numpy as np
>>> grid = pv.ImageData(dimensions=(5, 20, 20))
>>> scalars = grid.points - (grid.origin)
>>> scalars /= scalars.max()
>>> opacity = np.linalg.norm(
... grid.points - grid.center, axis=1
... ).reshape(-1, 1)
>>> opacity /= opacity.max()
>>> scalars = np.hstack((scalars, opacity**3))
>>> scalars *= 255
>>> pl = pv.Plotter()
>>> vol = pl.add_volume(grid, scalars=scalars.astype(np.uint8))
>>> vol.prop.interpolation_type = 'linear'
>>> pl.show()
Plot an UnstructuredGrid.
>>> from pyvista import examples
>>> import pyvista as pv
>>> mesh = examples.download_letter_a()
>>> mesh['scalars'] = mesh.points[:, 1]
>>> pl = pv.Plotter()
>>> _ = pl.add_volume(mesh, opacity_unit_distance=0.1)
>>> pl.show()
"""
# Handle default arguments
if user_matrix is None:
user_matrix = np.eye(4)
# Supported aliases
clim = kwargs.pop('rng', clim)
cmap = kwargs.pop('colormap', cmap)
culling = kwargs.pop('backface_culling', culling)
if "scalar" in kwargs:
raise TypeError(
"`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?",
)
assert_empty_kwargs(**kwargs)
if show_scalar_bar is None:
show_scalar_bar = self._theme.show_scalar_bar or scalar_bar_args
# Avoid mutating input
scalar_bar_args = {} if scalar_bar_args is None else scalar_bar_args.copy()
if culling is True:
culling = 'backface'
if mapper is None:
# Default mapper choice. Overridden later if UnstructuredGrid
mapper = self._theme.volume_mapper
# only render when the plotter has already been shown
if render is None:
render = not self._first_time
# Convert the VTK data object to a pyvista wrapped object if necessary
if not is_pyvista_dataset(volume):
if isinstance(volume, np.ndarray):
volume = wrap(volume)
if resolution is None:
resolution = [1, 1, 1]
elif len(resolution) != 3:
raise ValueError('Invalid resolution dimensions.')
volume.spacing = resolution
else:
volume = wrap(volume)
if not is_pyvista_dataset(volume):
raise TypeError(
f'Object type ({type(volume)}) not supported for plotting in PyVista.',
)
else:
# HACK: Make a copy so the original object is not altered.
# Also, place all data on the nodes as issues arise when
# volume rendering on the cells.
volume = volume.cell_data_to_point_data()
if name is None:
name = f'{type(volume).__name__}({volume.memory_address})'
if isinstance(volume, pyvista.MultiBlock):
from itertools import cycle
cycler = cycle(['Reds', 'Greens', 'Blues', 'Greys', 'Oranges', 'Purples'])
# Now iteratively plot each element of the multiblock dataset
actors = []
for idx in range(volume.GetNumberOfBlocks()):
if volume[idx] is None:
continue
# Get a good name to use
next_name = f'{name}-{idx}'
# Get the data object
block = wrap(volume.GetBlock(idx))
if resolution is None:
try:
block_resolution = block.GetSpacing()
except AttributeError:
block_resolution = resolution
else:
block_resolution = resolution
color = next(cycler) if multi_colors else cmap
a = self.add_volume(
block,
resolution=block_resolution,
opacity=opacity,
n_colors=n_colors,
cmap=color,
flip_scalars=flip_scalars,
reset_camera=reset_camera,
name=next_name,
ambient=ambient,
categories=categories,
culling=culling,
clim=clim,
mapper=mapper,
pickable=pickable,
opacity_unit_distance=opacity_unit_distance,
shade=shade,
diffuse=diffuse,
specular=specular,
specular_power=specular_power,
render=render,
show_scalar_bar=show_scalar_bar,
)
actors.append(a)
return actors
# Make sure structured grids are not less than 3D
# ImageData and RectilinearGrid should be olay as <3D
if isinstance(volume, pyvista.StructuredGrid):
if any(d < 2 for d in volume.dimensions):
raise ValueError('StructuredGrids must be 3D dimensional.')
if isinstance(volume, pyvista.PolyData):
raise TypeError(
f'Type {type(volume)} not supported for volume rendering as it is not 3D.',
)
elif not isinstance(
volume,
(pyvista.ImageData, pyvista.RectilinearGrid, pyvista.UnstructuredGrid),
):
volume = volume.cast_to_unstructured_grid()
# Override mapper choice for UnstructuredGrid
if isinstance(volume, pyvista.UnstructuredGrid):
# Unstructured grid must be all tetrahedrals
if not (volume.celltypes == pyvista.CellType.TETRA).all():
volume = volume.triangulate()
mapper = 'ugrid'
if mapper == 'fixed_point' and not isinstance(volume, pyvista.ImageData):
raise TypeError(
f'Type {type(volume)} not supported for volume rendering with the `"fixed_point"` mapper. Use `pyvista.ImageData`.',
)
elif isinstance(volume, pyvista.UnstructuredGrid) and mapper != 'ugrid':
raise TypeError(
f'Type {type(volume)} not supported for volume rendering with the `{mapper}` mapper. Use the "ugrid" mapper or simply leave as None.',
)
if opacity_unit_distance is None and not isinstance(volume, pyvista.UnstructuredGrid):
opacity_unit_distance = volume.length / (np.mean(volume.dimensions) - 1)
if scalars is None:
# Make sure scalars components are not vectors/tuples
scalars = volume.active_scalars
# Don't allow plotting of string arrays by default
if scalars is not None and np.issubdtype(scalars.dtype, np.number):
scalar_bar_args.setdefault('title', volume.active_scalars_info[1])
else:
raise MissingDataError('No scalars to use for volume rendering.')
title = 'Data'
if isinstance(scalars, str):
title = scalars
scalars = get_array(volume, scalars, preference=preference, err=True)
scalar_bar_args.setdefault('title', title)
elif not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if scalars.ndim != 1:
if scalars.ndim != 2:
raise ValueError('`add_volume` only supports scalars with 1 or 2 dimensions')
if scalars.shape[1] != 4 or scalars.dtype != np.uint8:
raise ValueError(
'`add_volume` only supports scalars with 2 dimensions that have 4 components of datatype np.uint8.\n\n'
f'Scalars have shape {scalars.shape} and dtype {scalars.dtype.name!r}.',
)
if not np.issubdtype(scalars.dtype, np.number):
raise TypeError('Non-numeric scalars are currently not supported for volume rendering.')
if scalars.ndim != 1:
if scalars.ndim != 2:
raise ValueError('`add_volume` only supports scalars with 1 or 2 dimensions')
if scalars.shape[1] != 4 or scalars.dtype != np.uint8:
raise ValueError(
f'`add_volume` only supports scalars with 2 dimension that have 4 components of datatype np.uint8, scalars have shape {scalars.shape} and datatype {scalars.dtype}',
)
if opacity != 'linear':
opacity = 'linear'
warnings.warn('Ignoring custom opacity due to RGBA scalars.')
# Define mapper, volume, and add the correct properties
mappers_lookup = {
'fixed_point': FixedPointVolumeRayCastMapper,
'gpu': GPUVolumeRayCastMapper,
'open_gl': OpenGLGPUVolumeRayCastMapper,
'smart': SmartVolumeMapper,
'ugrid': UnstructuredGridVolumeRayCastMapper,
}
if not isinstance(mapper, str) or mapper not in mappers_lookup.keys():
raise TypeError(
f"Mapper ({mapper}) unknown. Available volume mappers include: {', '.join(mappers_lookup.keys())}",
)
self.mapper = mappers_lookup[mapper](theme=self._theme)
# Set scalars range
min_, max_ = None, None
if clim is None:
if scalars.dtype == np.uint8:
clim = [0, 255]
else:
min_, max_ = np.nanmin(scalars), np.nanmax(scalars)
clim = [min_, max_]
elif isinstance(clim, (float, int)):
clim = [-clim, clim]
if log_scale:
if clim[0] <= 0:
clim = [sys.float_info.min, clim[1]]
# data must be between [0, 255], but not necessarily UINT8
# Preserve backwards compatibility and have same behavior as VTK.
if scalars.dtype != np.uint8 and clim != [0, 255]:
# must copy to avoid modifying inplace and remove any VTK weakref
scalars = np.array(scalars)
clim = np.asarray(clim, dtype=scalars.dtype)
scalars.clip(clim[0], clim[1], out=scalars)
if log_scale:
out = mpl.colors.LogNorm(clim[0], clim[1])(scalars)
scalars = out.data * 255
else:
if min_ is None:
min_, max_ = np.nanmin(scalars), np.nanmax(scalars)
np.true_divide((scalars - min_), (max_ - min_) / 255, out=scalars, casting='unsafe')
volume[title] = scalars
volume.active_scalars_name = title
# Scalars interpolation approach
if scalars.shape[0] == volume.n_points:
self.mapper.scalar_map_mode = 'point'
elif scalars.shape[0] == volume.n_cells:
self.mapper.scalar_map_mode = 'cell'
else:
raise_not_matching(scalars, volume)
self.mapper.scalar_range = clim
if isinstance(cmap, pyvista.LookupTable):
self.mapper.lookup_table = cmap
else:
if cmap is None:
cmap = self._theme.cmap
cmap = get_cmap_safe(cmap)
if categories:
if categories is True:
n_colors = len(np.unique(scalars))
elif isinstance(categories, int):
n_colors = categories
if flip_scalars:
cmap = cmap.reversed()
# Set colormap and build lookup table
self.mapper.lookup_table.apply_cmap(cmap, n_colors)
self.mapper.lookup_table.apply_opacity(opacity)
self.mapper.lookup_table.scalar_range = clim
self.mapper.lookup_table.log_scale = log_scale
if isinstance(annotations, dict):
self.mapper.lookup_table.annotations = annotations
self.mapper.dataset = volume
self.mapper.blend_mode = blending
self.mapper.update()
self.volume = Volume()
self.volume.mapper = self.mapper
self.volume.user_matrix = user_matrix
self.volume.prop = VolumeProperty(
lookup_table=self.mapper.lookup_table,
ambient=ambient,
shade=shade,
specular=specular,
specular_power=specular_power,
diffuse=diffuse,
opacity_unit_distance=opacity_unit_distance,
)
if scalars.ndim == 2:
self.volume.prop.independent_components = False
show_scalar_bar = False
actor, prop = self.add_actor(
self.volume,
reset_camera=reset_camera,
name=name,
culling=culling,
pickable=pickable,
render=render,
)
# Add scalar bar if scalars are available
if show_scalar_bar and scalars is not None:
self.add_scalar_bar(**scalar_bar_args)
self.renderer.Modified()
return actor
def add_silhouette(
self,
mesh,
color=None,
line_width=None,
opacity=None,
feature_angle=None,
decimate=None,
):
"""Add a silhouette of a PyVista or VTK dataset to the scene.
A silhouette can also be generated directly in
:func:`add_mesh <pyvista.Plotter.add_mesh>`. See also
:ref:`silhouette_example`.
Parameters
----------
mesh : pyvista.DataSet | vtk.vtkAlgorithm
Mesh or mesh-producing algorithm for generating silhouette
to plot.
color : ColorLike, optional
Color of the silhouette lines.
line_width : float, optional
Silhouette line width.
opacity : float, optional
Line transparency between ``0`` and ``1``.
feature_angle : float, optional
If set, display sharp edges exceeding that angle in degrees.
decimate : float, optional
Level of decimation between ``0`` and ``1``. Decimating will
improve rendering performance. A good rule of thumb is to
try ``0.9`` first and decrease until the desired rendering
performance is achieved.
Returns
-------
pyvista.Actor
Actor of the silhouette.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> bunny = examples.download_bunny()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(bunny, color='lightblue')
>>> _ = plotter.add_silhouette(bunny, color='red', line_width=8.0)
>>> plotter.view_xy()
>>> plotter.show()
"""
mesh, algo = algorithm_to_mesh_handler(mesh)
if not isinstance(mesh, pyvista.PolyData):
algo = extract_surface_algorithm(algo or mesh)
mesh, algo = algorithm_to_mesh_handler(algo)
silhouette_params = self._theme.silhouette.to_dict()
if color is None:
color = silhouette_params["color"]
if line_width is None:
line_width = silhouette_params["line_width"]
if opacity is None:
opacity = silhouette_params["opacity"]
if feature_angle is None:
feature_angle = silhouette_params["feature_angle"]
if decimate is None:
decimate = silhouette_params["decimate"]
# At this point we are dealing with a pipeline, so no `algo or mesh`
if decimate:
# Always triangulate as decimation filters needs it
# and source mesh could have been any type
algo = triangulate_algorithm(algo or mesh)
algo = decimation_algorithm(algo, decimate)
mesh, algo = algorithm_to_mesh_handler(algo)
alg = _vtk.vtkPolyDataSilhouette()
set_algorithm_input(alg, algo or mesh)
alg.SetCamera(self.renderer.camera)
if feature_angle is not None:
alg.SetEnableFeatureAngle(True)
alg.SetFeatureAngle(feature_angle)
else:
alg.SetEnableFeatureAngle(False)
mapper = DataSetMapper(theme=self._theme)
mapper.SetInputConnection(alg.GetOutputPort())
actor, prop = self.add_actor(mapper)
prop.SetColor(Color(color).float_rgb)
prop.SetOpacity(opacity)
prop.SetLineWidth(line_width)
return actor
def update_scalar_bar_range(self, clim, name=None):
"""Update the value range of the active or named scalar bar.
Parameters
----------
clim : sequence[float]
The new range of scalar bar. For example ``[-1, 2]``.
name : str, optional
The title of the scalar bar to update.
"""
if isinstance(clim, (float, int)):
clim = [-clim, clim]
if len(clim) != 2:
raise TypeError('clim argument must be a length 2 iterable of values: (min, max).')
if name is None:
if not hasattr(self, 'mapper'):
raise AttributeError('This plotter does not have an active mapper.')
self.mapper.scalar_range = clim
return
try:
# use the name to find the desired actor
for mh in self.scalar_bars._scalar_bar_mappers[name]:
mh.scalar_range = clim
except KeyError:
raise ValueError(f'Name ({name!r}) not valid/not found in this plotter.') from None
def clear_actors(self):
"""Clear actors from all renderers."""
self.renderers.clear_actors()
def clear(self):
"""Clear plot by removing all actors and properties.
Examples
--------
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(pv.Sphere())
>>> plotter.clear()
>>> plotter.renderer.actors
{}
"""
self.renderers.clear()
self.scalar_bars.clear()
self.mesh = None
self.mapper = None
def link_views(self, views=0):
"""Link the views' cameras.
Parameters
----------
views : int | tuple | list, default: 0
If ``views`` is int, link the views to the given view
index or if ``views`` is a tuple or a list, link the given
views cameras.
Examples
--------
Not linked view case.
>>> import pyvista as pv
>>> from pyvista import demos
>>> ocube = demos.orientation_cube()
>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.camera_position = 'yz'
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.show_axes()
>>> pl.show()
Linked view case.
>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.camera_position = 'yz'
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
>>> _ = pl.add_mesh(ocube['x_p'], color='blue')
>>> _ = pl.add_mesh(ocube['x_n'], color='blue')
>>> _ = pl.add_mesh(ocube['y_p'], color='green')
>>> _ = pl.add_mesh(ocube['y_n'], color='green')
>>> _ = pl.add_mesh(ocube['z_p'], color='red')
>>> _ = pl.add_mesh(ocube['z_n'], color='red')
>>> pl.show_axes()
>>> pl.link_views()
>>> pl.show()
"""
if isinstance(views, (int, np.integer)):
camera = self.renderers[views].camera
camera_status = self.renderers[views].camera.is_set
for renderer in self.renderers:
renderer.camera = camera
renderer.camera.is_set = camera_status
return
views = np.asarray(views)
if np.issubdtype(views.dtype, np.integer):
camera = self.renderers[views[0]].camera
camera_status = self.renderers[views[0]].camera.is_set
for view_index in views:
self.renderers[view_index].camera = camera
self.renderers[view_index].camera.is_set = camera_status
else:
raise TypeError(f'Expected type is int, list or tuple: {type(views)} is given')
def unlink_views(self, views=None):
"""Unlink the views' cameras.
Parameters
----------
views : int | tuple | list, optional
If ``views`` is None unlink all the views, if ``views``
is int unlink the selected view's camera or if ``views``
is a tuple or a list, unlink the given views cameras.
"""
if views is None:
for renderer in self.renderers:
renderer.camera = Camera()
renderer.reset_camera()
renderer.camera.is_set = False
elif isinstance(views, int):
self.renderers[views].camera = Camera()
self.renderers[views].reset_camera()
self.renderers[views].camera.is_set = False
elif isinstance(views, Iterable):
for view_index in views:
self.renderers[view_index].camera = Camera()
self.renderers[view_index].reset_camera()
self.renderers[view_index].cemera_set = False
else:
raise TypeError(f'Expected type is None, int, list or tuple: {type(views)} is given')
@wraps(ScalarBars.add_scalar_bar)
def add_scalar_bar(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap for ``ScalarBars.add_scalar_bar``."""
# only render when the plotter has already been shown
render = kwargs.get('render', None)
if render is None:
kwargs['render'] = not self._first_time
# check if maper exists
mapper = kwargs.get('mapper', None)
if mapper is None:
if not hasattr(self, 'mapper') or self.mapper is None:
raise AttributeError('Mapper does not exist. Add a mesh with scalars first.')
kwargs['mapper'] = self.mapper
# title can be the first and only arg
title = args[0] if len(args) else kwargs.get("title", "")
if title is None:
title = ''
kwargs['title'] = title
interactive = kwargs.get('interactive', None)
if interactive is None:
interactive = self._theme.interactive
if self.shape != (1, 1):
interactive = False
elif interactive and self.shape != (1, 1):
raise ValueError('Interactive scalar bars disabled for multi-renderer plots')
# by default, use the plotter local theme
kwargs.setdefault('theme', self._theme)
return self.scalar_bars.add_scalar_bar(**kwargs)
def update_scalars(self, scalars, mesh=None, render=True):
"""Update scalars of an object in the plotter.
.. deprecated:: 0.43.0
This method is deprecated and will be removed in a future version of
PyVista. It is functionally equivalent to directly modifying the
scalars of a mesh in-place.
.. code:: python
# Modify the points in place
mesh["my scalars"] = values
# Explicitly call render if needed
plotter.render()
Parameters
----------
scalars : sequence
Scalars to replace existing scalars.
mesh : vtk.PolyData | vtk.UnstructuredGrid, optional
Object that has already been added to the Plotter. If
None, uses last added mesh.
render : bool, default: True
Force a render when True.
"""
# Deprecated on 0.43.0, estimated removal on v0.46.0
warnings.warn(
"This method is deprecated and will be removed in a future version of "
"PyVista. Directly modify the scalars of a mesh in-place instead.",
PyVistaDeprecationWarning,
)
if mesh is None:
mesh = self.mesh
if isinstance(mesh, (Iterable, pyvista.MultiBlock)):
# Recursive if need to update scalars on many meshes
for m in mesh:
self.update_scalars(scalars, mesh=m, render=False)
if render:
self.render()
return
if isinstance(scalars, str):
# Grab scalars array if name given
scalars = get_array(mesh, scalars)
if scalars is None:
if render:
self.render()
return
if scalars.shape[0] == mesh.GetNumberOfPoints():
data = mesh.GetPointData()
elif scalars.shape[0] == mesh.GetNumberOfCells():
data = mesh.GetCellData()
else:
raise_not_matching(scalars, mesh)
vtk_scalars = data.GetScalars()
if vtk_scalars is None:
raise ValueError('No active scalars')
s = convert_array(vtk_scalars)
s[:] = scalars
vtk_scalars.Modified()
data.Modified()
with contextlib.suppress(Exception):
# Why are the points updated here? Not all datasets have points
# and only the scalars array is modified by this function...
mesh.GetPoints().Modified()
if render:
self.render()
def update_coordinates(self, points, mesh=None, render=True):
"""Update the points of an object in the plotter.
.. deprecated:: 0.43.0
This method is deprecated and will be removed in a future version of
PyVista. It is functionally equivalent to directly modifying the
points of a mesh in-place.
.. code:: python
# Modify the points in place
mesh.points = points
# Explicitly call render if needed
plotter.render()
Parameters
----------
points : np.ndarray
Points to replace existing points.
mesh : vtk.PolyData | vtk.UnstructuredGrid, optional
Object that has already been added to the Plotter. If ``None``, uses
last added mesh.
render : bool, default: True
Force a render when True.
"""
# Deprecated on 0.43.0, estimated removal on v0.46.0
warnings.warn(
"This method is deprecated and will be removed in a future version of "
"PyVista. Directly modify the points of a mesh in-place instead.",
PyVistaDeprecationWarning,
)
if mesh is None:
mesh = self.mesh
mesh.points = points
# only render when the plotter has already been shown
if render is None:
render = not self._first_time
if render:
self.render()
def _clear_ren_win(self):
"""Clear the render window."""
# Not using `render_window` property here to enforce clean up
if hasattr(self, 'ren_win'):
self.ren_win.Finalize()
del self.ren_win
def close(self):
"""Close the render window."""
# optionally run just prior to exiting the plotter
if self._before_close_callback is not None:
self._before_close_callback(self)
self._before_close_callback = None
# must close out widgets first
super().close()
# Renderer has an axes widget, so close it
self.renderers.close()
self.renderers.remove_all_lights()
# Grab screenshots of last render
# self.last_image = self.screenshot(None, return_img=True)
# self.last_image_depth = self.get_image_depth()
# reset scalar bars
self.scalar_bars.clear()
self.mesh = None
self.mapper = None
# grab the display id before clearing the window
# this is an experimental feature
if KILL_DISPLAY: # pragma: no cover
disp_id = None
if self.render_window is not None:
disp_id = self.render_window.GetGenericDisplayId()
self._clear_ren_win()
if self.iren is not None:
self.iren.close()
if KILL_DISPLAY: # pragma: no cover
_kill_display(disp_id)
self.iren = None
if hasattr(self, 'text'):
del self.text
# end movie
if hasattr(self, 'mwriter'):
with suppress(BaseException):
self.mwriter.close()
# Remove the global reference to this plotter unless building the
# gallery to allow it to collect.
if not pyvista.BUILDING_GALLERY:
if _ALL_PLOTTERS is not None:
_ALL_PLOTTERS.pop(self._id_name, None)
# this helps managing closed plotters
self._closed = True
def deep_clean(self):
"""Clean the plotter of the memory."""
self.disable_picking()
if hasattr(self, 'renderers'):
self.renderers.deep_clean()
self.mesh = None
self.mapper = None
self.volume = None
self.text = None
def add_text(
self,
text,
position='upper_left',
font_size=18,
color=None,
font=None,
shadow=False,
name=None,
viewport=False,
orientation=0.0,
font_file=None,
*,
render=True,
):
"""Add text to plot object in the top left corner by default.
Parameters
----------
text : str
The text to add the rendering.
position : str | sequence[float], default: "upper_left"
Position to place the bottom left corner of the text box.
If tuple is used, the position of the text uses the pixel
coordinate system (default). In this case,
it returns a more general `vtkOpenGLTextActor`.
If string name is used, it returns a `vtkCornerAnnotation`
object normally used for fixed labels (like title or xlabel).
Default is to find the top left corner of the rendering window
and place text box up there. Available position: ``'lower_left'``,
``'lower_right'``, ``'upper_left'``, ``'upper_right'``,
``'lower_edge'``, ``'upper_edge'``, ``'right_edge'``, and
``'left_edge'``.
font_size : float, default: 18
Sets the size of the title font.
color : ColorLike, optional
Either a string, RGB list, or hex color string. For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
Defaults to :attr:`pyvista.global_theme.font.color <pyvista.plotting.themes._Font.color>`.
font : str, default: 'arial'
Font name may be ``'courier'``, ``'times'``, or ``'arial'``.
This is ignored if the `font_file` is set.
shadow : bool, default: False
Adds a black shadow to the text.
name : str, optional
The name for the added actor so that it can be easily updated.
If an actor of this name already exists in the rendering window, it
will be replaced by the new actor.
viewport : bool, default: False
If ``True`` and position is a tuple of float, uses the
normalized viewport coordinate system (values between 0.0
and 1.0 and support for HiDPI).
orientation : float, default: 0.0
Angle orientation of text counterclockwise in degrees. The text
is rotated around an anchor point that may be on the edge or
corner of the text. The default is horizontal (0.0 degrees).
font_file : str, default: None
The absolute file path to a local file containing a freetype
readable font.
render : bool, default: True
Force a render when ``True``.
Returns
-------
vtk.vtkTextActor
Text actor added to plot.
Examples
--------
Add blue text to the upper right of the plotter.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_text(
... 'Sample Text',
... position='upper_right',
... color='blue',
... shadow=True,
... font_size=26,
... )
>>> pl.show()
Add text and use a custom freetype readable font file.
>>> pl = pv.Plotter()
>>> actor = pl.add_text(
... 'Text',
... font_file='/home/user/Mplus2-Regular.ttf',
... ) # doctest:+SKIP
"""
if font_size is None:
font_size = self._theme.font.size
if position is None:
# Set the position of the text to the top left corner
window_size = self.window_size
x = (window_size[0] * 0.02) / self.shape[0]
y = (window_size[1] * 0.85) / self.shape[0]
position = [x, y]
text_prop = TextProperty(
color=color,
font_family=font,
orientation=orientation,
font_file=font_file,
shadow=shadow,
)
if isinstance(position, (int, str, bool)):
self.text = CornerAnnotation(position, text, linear_font_scale_factor=font_size // 2)
else:
self.text = Text(text=text, position=position)
if viewport:
self.text.GetActualPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
self.text.GetActualPosition2Coordinate().SetCoordinateSystemToNormalizedViewport()
text_prop.font_size = int(font_size * 2)
self.text.prop = text_prop
self.add_actor(self.text, reset_camera=False, name=name, pickable=False, render=render)
return self.text
def open_movie(self, filename, framerate=24, quality=5, **kwargs):
"""Establish a connection to the ffmpeg writer.
Requires ``imageio`` to be installed.
Parameters
----------
filename : str | Path
Filename of the movie to open. Filename should end in mp4,
but other filetypes may be supported. See :func:`imageio.get_writer()
<imageio.v2.get_writer>`.
framerate : int, default: 24
Frames per second.
quality : int, default: 5
Quality 10 is the top possible quality for any codec. The
range is ``0 - 10``. Higher quality leads to a larger file.
**kwargs : dict, optional
See the documentation for :func:`imageio.get_writer()
<imageio.v2.get_writer>` for additional kwargs.
Notes
-----
See the documentation for :func:`imageio.get_writer() <imageio.v2.get_writer>`.
Examples
--------
Open a MP4 movie and set the quality to maximum.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.open_movie('movie.mp4', quality=10) # doctest:+SKIP
"""
try:
from imageio import get_writer
except ModuleNotFoundError: # pragma: no cover
raise ModuleNotFoundError(
'Install imageio to use `open_movie` with:\n\n pip install imageio',
) from None
if (
isinstance(pyvista.FIGURE_PATH, str) and not Path(filename).is_absolute()
): # pragma: no cover
filename = Path(pyvista.FIGURE_PATH) / filename
self.mwriter = get_writer(filename, fps=framerate, quality=quality, **kwargs)
def open_gif(
self,
filename,
loop=0,
fps=10,
palettesize=256,
subrectangles=False,
**kwargs,
):
"""Open a gif file.
Requires ``imageio`` to be installed.
Parameters
----------
filename : str | Path
Filename of the gif to open. Filename must end in ``"gif"``.
loop : int, default: 0
The number of iterations. Default value of 0 loops indefinitely.
fps : float, default: 10
The number of frames per second. If duration is not given, the
duration for each frame is set to 1/fps.
palettesize : int, default: 256
The number of colors to quantize the image to. Is rounded to the
nearest power of two. Must be between 2 and 256.
subrectangles : bool, default: False
If ``True``, will try and optimize the GIF by storing only the rectangular
parts of each frame that change with respect to the previous.
.. note::
Setting this to ``True`` may help reduce jitter in colorbars.
**kwargs : dict, optional
See the documentation for :func:`imageio.get_writer() <imageio.v2.get_writer>`
for additional kwargs.
Notes
-----
Consider using `pygifsicle
<https://github.com/LucaCappelletti94/pygifsicle>`_ to reduce the final
size of the gif. See `Optimizing a GIF using pygifsicle
<https://imageio.readthedocs.io/en/stable/examples.html#optimizing-a-gif-using-pygifsicle>`_.
Examples
--------
Open a gif file, setting the framerate to 8 frames per second and
reducing the colorspace to 64.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.open_gif(
... 'movie.gif', fps=8, palettesize=64
... ) # doctest:+SKIP
See :ref:`gif_movie_example` for a full example using this method.
"""
try:
from imageio import __version__
from imageio import get_writer
except ModuleNotFoundError: # pragma: no cover
raise ModuleNotFoundError(
'Install imageio to use `open_gif` with:\n\n pip install imageio',
) from None
filename = Path(filename)
if not filename.suffix == '.gif':
raise ValueError('Unsupported filetype. Must end in .gif')
if isinstance(pyvista.FIGURE_PATH, str) and not filename.is_absolute(): # pragma: no cover
filename = Path(pyvista.FIGURE_PATH) / filename
self._gif_filename = filename.resolve()
kwargs['mode'] = 'I'
kwargs['loop'] = loop
kwargs['palettesize'] = palettesize
kwargs['subrectangles'] = subrectangles
if scooby.meets_version(__version__, '2.28.1'):
kwargs['duration'] = 1000 * 1 / fps
else: # pragma: no cover
kwargs['fps'] = fps
self.mwriter = get_writer(filename, **kwargs)
def write_frame(self):
"""Write a single frame to the movie file.
Examples
--------
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> plotter.open_movie(filename) # doctest:+SKIP
>>> plotter.add_mesh(pv.Sphere()) # doctest:+SKIP
>>> plotter.write_frame() # doctest:+SKIP
See :ref:`movie_example` for a full example using this method.
"""
# if off screen, show has not been called and we must render
# before extracting an image
if self._first_time:
self._on_first_render_request()
self.render()
if not hasattr(self, 'mwriter'):
raise RuntimeError('This plotter has not opened a movie or GIF file.')
self.update()
self.mwriter.append_data(self.image)
def get_image_depth(self, fill_value=np.nan, reset_camera_clipping_range=True):
"""Return a depth image representing current render window.
Parameters
----------
fill_value : float, default: numpy.nan
Fill value for points in image that do not include objects
in scene. To not use a fill value, pass ``None``.
reset_camera_clipping_range : bool, default: True
Reset the camera clipping range to include data in view.
Returns
-------
pyvista.pyvista_ndarray
Image of depth values from camera orthogonal to image
plane.
Notes
-----
Values in image_depth are negative to adhere to a
right-handed coordinate system.
Examples
--------
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(pv.Sphere())
>>> plotter.show()
>>> zval = plotter.get_image_depth()
"""
# allow no render window
if self.render_window is None and self.last_image_depth is not None:
zval = self.last_image_depth.copy()
if fill_value is not None:
zval[self._image_depth_null] = fill_value
return zval
self._check_rendered()
self._check_has_ren_win()
# Ensure points in view are within clipping range of renderer?
if reset_camera_clipping_range:
self.renderer.ResetCameraClippingRange()
# Get the z-buffer image
ifilter = _vtk.vtkWindowToImageFilter()
ifilter.SetInput(self.render_window)
ifilter.SetScale(self.image_scale)
ifilter.ReadFrontBufferOff()
ifilter.SetInputBufferTypeToZBuffer()
zbuff = run_image_filter(ifilter)[:, :, 0]
# Convert z-buffer values to depth from camera
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
near, far = self.camera.clipping_range
if self.camera.parallel_projection:
zval = (zbuff - near) / (far - near)
else:
zval = 2 * near * far / ((zbuff - 0.5) * 2 * (far - near) - near - far)
# Consider image values outside clipping range as nans
self._image_depth_null = np.logical_or(zval < -far, np.isclose(zval, -far))
if fill_value is not None:
zval[self._image_depth_null] = fill_value
return zval
def add_lines(self, lines, color='w', width=5, label=None, name=None, connected=False):
"""Add lines to the plotting object.
Parameters
----------
lines : np.ndarray
Points representing line segments. For example, two line
segments would be represented as ``np.array([[0, 1, 0],
[1, 0, 0], [1, 1, 0], [2, 0, 0]])``.
color : ColorLike, default: 'w'
Either a string, rgb list, or hex color string. For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
width : float, default: 5
Thickness of lines.
label : str, default: None
String label to use when adding a legend to the scene with
:func:`pyvista.Plotter.add_legend`.
name : str, default: None
The name for the added actor so that it can be easily updated.
If an actor of this name already exists in the rendering window, it
will be replaced by the new actor.
connected : bool, default: False
Treat ``lines`` as points representing a series of *connected* lines.
For example, two connected line segments would be represented as
``np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]])``. If ``False``, an *even*
number of points must be passed to ``lines``, and the lines need not be
connected.
Returns
-------
vtk.vtkActor
Lines actor.
Examples
--------
Plot two lines.
>>> import numpy as np
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
>>> actor = pl.add_lines(points, color='purple', width=3)
>>> pl.camera_position = 'xy'
>>> pl.show()
Adding lines with ``connected=True`` will add a series of connected
line segments.
>>> pl = pv.Plotter()
>>> points = np.array([[0, 1, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]])
>>> actor = pl.add_lines(
... points, color='purple', width=3, connected=True
... )
>>> pl.camera_position = 'xy'
>>> pl.show()
"""
if not isinstance(lines, np.ndarray):
raise TypeError('Input should be an array of point segments')
lines = (
pyvista.lines_from_points(lines)
if connected
else pyvista.line_segments_from_points(lines)
)
actor = Actor(mapper=DataSetMapper(lines))
actor.prop.line_width = width
actor.prop.show_edges = True
actor.prop.edge_color = color
actor.prop.color = color
actor.prop.lighting = False
# legend label
if label:
if not isinstance(label, str):
raise TypeError('Label must be a string')
addr = actor.GetAddressAsString("")
self.renderer._labels[addr] = [lines, label, Color(color)]
# Add to renderer
self.add_actor(actor, reset_camera=False, name=name, pickable=False)
return actor
@wraps(ScalarBars.remove_scalar_bar)
def remove_scalar_bar(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Remove the active scalar bar."""
self.scalar_bars.remove_scalar_bar(*args, **kwargs)
def add_point_labels(
self,
points,
labels,
italic=False,
bold=True,
font_size=None,
text_color=None,
font_family=None,
shadow=False,
show_points=True,
point_color=None,
point_size=None,
name=None,
shape_color='grey',
shape='rounded_rect',
fill_shape=True,
margin=3,
shape_opacity=1.0,
pickable=False,
render_points_as_spheres=False,
tolerance=0.001,
reset_camera=None,
always_visible=False,
render=True,
justification_horizontal=None,
justification_vertical=None,
background_color=None,
background_opacity=None,
):
"""Create a point actor with one label from list labels assigned to each point.
Parameters
----------
points : sequence | pyvista.DataSet | vtk.vtkAlgorithm
An ``n x 3`` sequence points or :class:`pyvista.DataSet` with
points or mesh-producing algorithm.
labels : list | str
List of labels. Must be the same length as points. If a
string name is given with a :class:`pyvista.DataSet` input for
points, then these are fetched.
italic : bool, default: False
Italicises title and bar labels.
bold : bool, default: True
Bolds title and bar labels.
font_size : float, optional
Sets the size of the title font.
text_color : ColorLike, optional
Color of text. Either a string, RGB sequence, or hex color string.
* ``text_color='white'``
* ``text_color='w'``
* ``text_color=[1.0, 1.0, 1.0]``
* ``text_color='#FFFFFF'``
font_family : str, optional
Font family. Must be either ``'courier'``, ``'times'``,
or ``'arial``.
shadow : bool, default: False
Adds a black shadow to the text.
show_points : bool, default: True
Controls if points are visible.
point_color : ColorLike, optional
Either a string, rgb list, or hex color string. One of
the following.
* ``point_color='white'``
* ``point_color='w'``
* ``point_color=[1.0, 1.0, 1.0]``
* ``point_color='#FFFFFF'``
point_size : float, optional
Size of points if visible.
name : str, optional
The name for the added actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
shape_color : ColorLike, default: "grey"
Color of shape (if visible). Either a string, rgb
sequence, or hex color string.
shape : str, default: "rounded_rect"
The string name of the shape to use. Options are ``'rect'`` or
``'rounded_rect'``. If you want no shape, pass ``None``.
fill_shape : bool, default: True
Fill the shape with the ``shape_color``. Outlines if ``False``.
margin : int, default: 3
The size of the margin on the label background shape.
shape_opacity : float, default: 1.0
The opacity of the shape in the range of ``[0, 1]``.
pickable : bool, default: False
Set whether this actor is pickable.
render_points_as_spheres : bool, default: False
Render points as spheres rather than dots.
tolerance : float, default: 0.001
A tolerance to use to determine whether a point label is
visible. A tolerance is usually required because the
conversion from world space to display space during
rendering introduces numerical round-off.
reset_camera : bool, optional
Reset the camera after adding the points to the scene.
always_visible : bool, default: False
Skip adding the visibility filter.
render : bool, default: True
Force a render when ``True``.
justification_horizontal : str, optional
Text's horizontal justification.
Should be either "left", "center" or "right".
.. warning::
If the justification is not default,
the shape will be out of alignment with the label.
If you use other than default,
Please use the background color.
See: https://github.com/pyvista/pyvista/pull/5407
justification_vertical : str, optional
Text's vertical justification.
Should be either "bottom", "center" or "top".
.. warning::
If the justification is not default,
the shape will be out of alignment with the label.
If you use other than default,
Please use the background color.
See: https://github.com/pyvista/pyvista/pull/5407
background_color : pyvista.Color, optional
Background color of text's property.
background_opacity : pyvista.Color, optional
Background opacity of text's property.
Returns
-------
vtk.vtkActor2D
VTK label actor. Can be used to change properties of the labels.
Examples
--------
>>> import numpy as np
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> points = np.array(
... [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [2.0, 0.0, 0.0]]
... )
>>> labels = ['Point A', 'Point B', 'Point C']
>>> actor = pl.add_point_labels(
... points,
... labels,
... italic=True,
... font_size=20,
... point_color='red',
... point_size=20,
... render_points_as_spheres=True,
... always_visible=True,
... shadow=True,
... )
>>> pl.camera_position = 'xy'
>>> pl.show()
"""
if font_family is None:
font_family = self._theme.font.family
if font_size is None:
font_size = self._theme.font.size
point_color = Color(point_color, default_color=self._theme.color)
if isinstance(points, (list, tuple)):
points = np.array(points)
if isinstance(points, np.ndarray):
points = pyvista.PolyData(points) # Cast to poly data
elif not is_pyvista_dataset(points) and not isinstance(points, _vtk.vtkAlgorithm):
raise TypeError(f'Points type not usable: {type(points)}')
points, algo = algorithm_to_mesh_handler(points)
if algo is not None:
if pyvista.vtk_version_info < (9, 1): # pragma: no cover
from pyvista.core.errors import VTKVersionError
raise VTKVersionError(
'To use vtkAlgorithms with `add_point_labels` requires VTK 9.1 or later.',
)
# Extract points filter
pc_algo = _vtk.vtkConvertToPointCloud()
set_algorithm_input(pc_algo, algo)
algo = pc_algo
if name is None:
name = f'{type(points).__name__}({points.memory_address})'
hier = _vtk.vtkPointSetToLabelHierarchy()
if not isinstance(labels, str):
if algo is not None:
raise TypeError(
'If using a vtkAlgorithm input, the labels must be a named array on the dataset.',
)
points = pyvista.PolyData(points.points)
if len(points.points) != len(labels):
raise ValueError('There must be one label for each point')
vtklabels = _vtk.vtkStringArray()
vtklabels.SetName('labels')
for item in labels:
vtklabels.InsertNextValue(str(item))
points.GetPointData().AddArray(vtklabels)
hier.SetLabelArrayName('labels')
else:
# Make sure PointData
if labels not in points.point_data:
raise ValueError(f'Array {labels!r} not found in point data.')
hier.SetLabelArrayName(labels)
if always_visible:
set_algorithm_input(hier, algo or points)
else:
# Only show visible points
vis_points = _vtk.vtkSelectVisiblePoints()
set_algorithm_input(vis_points, algo or points)
vis_points.SetRenderer(self.renderer)
vis_points.SetTolerance(tolerance)
hier.SetInputConnection(vis_points.GetOutputPort())
# create label mapper
label_mapper = _vtk.vtkLabelPlacementMapper()
label_mapper.SetInputConnection(hier.GetOutputPort())
if not isinstance(shape, str):
label_mapper.SetShapeToNone()
elif shape.lower() in 'rect':
label_mapper.SetShapeToRect()
elif shape.lower() in 'rounded_rect':
label_mapper.SetShapeToRoundedRect()
else:
raise ValueError(f'Shape ({shape}) not understood')
if fill_shape:
label_mapper.SetStyleToFilled()
else:
label_mapper.SetStyleToOutline()
label_mapper.SetBackgroundColor(Color(shape_color).float_rgb)
label_mapper.SetBackgroundOpacity(shape_opacity)
label_mapper.SetMargin(margin)
text_property = pyvista.TextProperty(
italic=italic,
bold=bold,
font_size=font_size,
font_family=font_family,
color=text_color,
shadow=shadow,
justification_horizontal=justification_horizontal,
justification_vertical=justification_vertical,
background_color=background_color,
background_opacity=background_opacity,
)
hier.SetTextProperty(text_property)
self.remove_actor(f'{name}-points', reset_camera=False)
self.remove_actor(f'{name}-labels', reset_camera=False)
# add points
if show_points:
self.add_mesh(
algo or points,
color=point_color,
point_size=point_size,
name=f'{name}-points',
pickable=pickable,
render_points_as_spheres=render_points_as_spheres,
reset_camera=reset_camera,
render=render,
)
label_actor = _vtk.vtkActor2D()
label_actor.SetMapper(label_mapper)
self.add_actor(label_actor, reset_camera=False, name=f'{name}-labels', pickable=False)
return label_actor
def add_point_scalar_labels(self, points, labels, fmt=None, preamble='', **kwargs):
"""Label the points from a dataset with the values of their scalars.
Wrapper for :func:`pyvista.Plotter.add_point_labels`.
Parameters
----------
points : sequence[float] | np.ndarray | pyvista.DataSet
An ``n x 3`` numpy.ndarray or pyvista dataset with points.
labels : list | str
List of scalars of labels. Must be the same length as points. If a
string name is given with a :class:`pyvista.DataSet` input for
points, then these are fetched.
fmt : str, optional
String formatter used to format numerical data.
preamble : str, default: ""
Text before the start of each label.
**kwargs : dict, optional
Keyword arguments passed to
:func:`pyvista.Plotter.add_point_labels`.
Returns
-------
vtk.vtkActor2D
VTK label actor. Can be used to change properties of the labels.
"""
if not is_pyvista_dataset(points):
points, _ = _coerce_pointslike_arg(points, copy=False)
if not isinstance(labels, (str, list)):
raise TypeError(
'labels must be a string name of the scalars array to use or list of scalars',
)
if fmt is None:
fmt = self._theme.font.fmt
if fmt is None:
fmt = '%.6e'
if isinstance(points, np.ndarray):
scalars = labels
elif is_pyvista_dataset(points):
scalars = points.point_data[labels]
phrase = f'{preamble} {fmt}'
labels = [phrase % val for val in scalars]
return self.add_point_labels(points, labels, **kwargs)
def add_points(self, points, style='points', **kwargs):
"""Add points to a mesh.
Parameters
----------
points : numpy.ndarray or pyvista.DataSet
Array of points or the points from a pyvista object.
style : str, default: 'points'
Visualization style of the mesh. One of the following:
``style='points'``, ``style='points_gaussian'``.
``'points_gaussian'`` can be controlled with the ``emissive`` and
``render_points_as_spheres`` options.
**kwargs : dict, optional
See :func:`pyvista.Plotter.add_mesh` for optional
keyword arguments.
Returns
-------
pyvista.Actor
Actor of the mesh.
Examples
--------
Add a numpy array of points to a mesh.
>>> import numpy as np
>>> import pyvista as pv
>>> rng = np.random.default_rng(seed=0)
>>> points = rng.random((10, 3))
>>> pl = pv.Plotter()
>>> actor = pl.add_points(
... points, render_points_as_spheres=True, point_size=100.0
... )
>>> pl.show()
Plot using the ``'points_gaussian'`` style
>>> points = rng.random((10, 3))
>>> pl = pv.Plotter()
>>> actor = pl.add_points(points, style='points_gaussian')
>>> pl.show()
"""
if style not in ['points', 'points_gaussian']:
raise ValueError(
f'Invalid style {style} for add_points. Should be either "points" or '
'"points_gaussian".',
)
return self.add_mesh(points, style=style, **kwargs)
def add_arrows(self, cent, direction, mag=1, **kwargs):
"""Add arrows to the plotter.
Parameters
----------
cent : np.ndarray
Array of centers.
direction : np.ndarray
Array of direction vectors.
mag : float, optional
Amount to scale the direction vectors.
**kwargs : dict, optional
See :func:`pyvista.Plotter.add_mesh` for optional
keyword arguments.
Returns
-------
pyvista.Actor
Actor of the arrows.
Examples
--------
Plot a random field of vectors and save a screenshot of it.
>>> import numpy as np
>>> import pyvista as pv
>>> rng = np.random.default_rng(seed=0)
>>> cent = rng.random((10, 3))
>>> direction = rng.random((10, 3))
>>> plotter = pv.Plotter()
>>> _ = plotter.add_arrows(cent, direction, mag=2)
>>> plotter.show()
"""
if cent.shape != direction.shape: # pragma: no cover
raise ValueError('center and direction arrays must have the same shape')
direction = direction.copy()
if cent.ndim != 2:
cent = cent.reshape((-1, 3))
if direction.ndim != 2:
direction = direction.reshape((-1, 3))
if mag != 1:
direction = direction * mag
pdata = pyvista.vector_poly_data(cent, direction)
# Create arrow object
arrow = _vtk.vtkArrowSource()
arrow.Update()
glyph3D = _vtk.vtkGlyph3D()
glyph3D.SetSourceData(arrow.GetOutput())
glyph3D.SetInputData(pdata)
glyph3D.SetVectorModeToUseVector()
glyph3D.Update()
arrows = wrap(glyph3D.GetOutput())
return self.add_mesh(arrows, **kwargs)
@staticmethod
def _save_image(image, filename, return_img):
"""Save to file and/or return a NumPy image array.
This is an internal helper.
"""
if not image.size:
raise ValueError('Empty image. Have you run plot() first?')
# write screenshot to file if requested
if isinstance(filename, (str, Path, io.BytesIO)):
from PIL import Image
if isinstance(filename, (str, Path)):
filename = Path(filename)
if isinstance(pyvista.FIGURE_PATH, str) and not filename.is_absolute():
filename = Path(pyvista.FIGURE_PATH) / filename
if not filename.suffix:
filename = filename.with_suffix('.png')
elif filename.suffix not in SUPPORTED_FORMATS:
raise ValueError(
f'Unsupported extension {filename.suffix}\n'
f'Must be one of the following: {SUPPORTED_FORMATS}',
)
filename = filename.expanduser().resolve()
Image.fromarray(image).save(filename)
else:
Image.fromarray(image).save(filename, format="PNG")
# return image array if requested
return image if return_img else None
def save_graphic(self, filename, title='PyVista Export', raster=True, painter=True):
"""Save a screenshot of the rendering window as a graphic file.
This can be helpful for publication documents.
The supported formats are:
* ``'.svg'``
* ``'.eps'``
* ``'.ps'``
* ``'.pdf'``
* ``'.tex'``
Parameters
----------
filename : str
Path to fsave the graphic file to.
title : str, default: "PyVista Export"
Title to use within the file properties.
raster : bool, default: True
Attempt to write 3D properties as a raster image.
painter : bool, default: True
Configure the exporter to expect a painter-ordered 2D
rendering, that is, a rendering at a fixed depth where
primitives are drawn from the bottom up.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(examples.load_airplane(), smooth_shading=True)
>>> _ = pl.add_background_image(examples.mapfile)
>>> pl.save_graphic("img.svg") # doctest:+SKIP
"""
from vtkmodules.vtkIOExportGL2PS import vtkGL2PSExporter
if self.render_window is None:
raise AttributeError('This plotter is closed and unable to save a screenshot.')
if self._first_time:
self._on_first_render_request()
self.render()
filename = Path(filename)
if isinstance(pyvista.FIGURE_PATH, str) and not filename.is_absolute(): # pragma: no cover
filename = Path(pyvista.FIGURE_PATH) / filename
filename = filename.expanduser().resolve()
extension = pyvista.core.utilities.fileio.get_ext(filename)
writer = vtkGL2PSExporter()
modes = {
'.svg': writer.SetFileFormatToSVG,
'.eps': writer.SetFileFormatToEPS,
'.ps': writer.SetFileFormatToPS,
'.pdf': writer.SetFileFormatToPDF,
'.tex': writer.SetFileFormatToTeX,
}
if extension not in modes:
raise ValueError(
f"Extension ({extension}) is an invalid choice.\n\n"
f"Valid options include: {', '.join(modes.keys())}",
)
writer.CompressOff()
if pyvista.vtk_version_info < (9, 2, 2): # pragma no cover
writer.SetFilePrefix(str(filename.with_suffix('')))
else:
writer.SetFilePrefix(filename.with_suffix(''))
writer.SetInput(self.render_window)
modes[extension]()
writer.SetTitle(title)
writer.SetWrite3DPropsAsRasterImage(raster)
if painter:
writer.UsePainterSettings()
writer.Update()
def screenshot(
self,
filename=None,
transparent_background=None,
return_img=True,
window_size=None,
scale=None,
):
"""Take screenshot at current camera position.
Parameters
----------
filename : str | Path | io.BytesIO, optional
Location to write image to. If ``None``, no image is written.
transparent_background : bool, optional
Whether to make the background transparent. The default is
looked up on the plotter's theme.
return_img : bool, default: True
If ``True``, a :class:`numpy.ndarray` of the image will be
returned.
window_size : sequence[int], optional
Set the plotter's size to this ``(width, height)`` before
taking the screenshot.
scale : int, optional
Set the factor to scale the window size to make a higher
resolution image. If ``None`` this will use the ``image_scale``
property on this plotter which defaults to one.
Returns
-------
pyvista.pyvista_ndarray
Array containing pixel RGB and alpha. Sized:
* [Window height x Window width x 3] if
``transparent_background`` is set to ``False``.
* [Window height x Window width x 4] if
``transparent_background`` is set to ``True``.
Examples
--------
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plotter = pv.Plotter(off_screen=True)
>>> actor = plotter.add_mesh(sphere)
>>> plotter.screenshot('screenshot.png') # doctest:+SKIP
"""
with self.window_size_context(window_size):
# configure image filter
if transparent_background is None:
transparent_background = self._theme.transparent_background
self.image_transparent_background = transparent_background
# This if statement allows you to save screenshots of closed plotters
# This is needed for the sphinx-gallery to work
if self.render_window is None:
# If plotter has been closed...
# check if last_image exists
if self.last_image is not None:
# Save last image
if scale is not None:
warnings.warn(
'This plotter is closed and cannot be scaled. Using the last saved image. Try using the `image_scale` property directly.',
)
return self._save_image(self.last_image, filename, return_img)
# Plotter hasn't been rendered or was improperly closed
raise RuntimeError('This plotter is closed and unable to save a screenshot.')
if self._first_time and not self.off_screen:
raise RuntimeError(
"Nothing to screenshot - call .show first or use the off_screen argument",
)
# if off screen, show has not been called and we must render
# before extracting an image
if self._first_time:
self._on_first_render_request()
self.render()
with self.image_scale_context(scale):
self._make_render_window_current()
return self._save_image(self.image, filename, return_img)
@wraps(Renderers.set_background)
def set_background(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderers.set_background``."""
self.renderers.set_background(*args, **kwargs)
@wraps(Renderers.set_color_cycler)
def set_color_cycler(self, *args, **kwargs): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderers.set_color_cycler``."""
self.renderers.set_color_cycler(*args, **kwargs)
def generate_orbital_path(self, factor=3.0, n_points=20, viewup=None, shift=0.0):
"""Generate an orbital path around the data scene.
Parameters
----------
factor : float, default: 3.0
A scaling factor when building the orbital extent.
n_points : int, default: 20
Number of points on the orbital path.
viewup : sequence[float], optional
The normal to the orbital plane.
shift : float, default: 0.0
Shift the plane up/down from the center of the scene by
this amount.
Returns
-------
pyvista.PolyData
PolyData containing the orbital path.
Examples
--------
Generate an orbital path around a sphere.
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(pv.Sphere())
>>> viewup = [0, 0, 1]
>>> orbit = plotter.generate_orbital_path(
... factor=2.0, n_points=50, shift=0.0, viewup=viewup
... )
See :ref:`orbiting_example` for a full example using this method.
"""
if viewup is None:
viewup = self._theme.camera.viewup
center = np.array(self.center)
bnds = np.array(self.bounds)
radius = (bnds[1] - bnds[0]) * factor
y = (bnds[3] - bnds[2]) * factor
if y > radius:
radius = y
center += np.array(viewup) * shift
return pyvista.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points)
def fly_to(self, point):
"""Move the current camera's focal point to a position point.
The movement is animated over the number of frames specified in
NumberOfFlyFrames. The LOD desired frame rate is used.
Parameters
----------
point : sequence[float]
Point to fly to in the form of ``(x, y, z)``.
"""
self.iren.fly_to(self.renderer, point)
def orbit_on_path(
self,
path=None,
focus=None,
step=0.5,
viewup=None,
write_frames=False,
threaded=False,
progress_bar=False,
):
"""Orbit on the given path focusing on the focus point.
Parameters
----------
path : pyvista.PolyData
Path of orbital points. The order in the points is the order of
travel.
focus : sequence[float], optional
The point of focus the camera. For example ``(0.0, 0.0, 0.0)``.
step : float, default: 0.5
The timestep between flying to each camera position. Ignored when
``plotter.off_screen = True``.
viewup : sequence[float], optional
The normal to the orbital plane.
write_frames : bool, default: False
Assume a file is open and write a frame on each camera
view during the orbit.
threaded : bool, default: False
Run this as a background thread. Generally used within a
GUI (i.e. PyQt).
progress_bar : bool, default: False
Show the progress bar when proceeding through the path.
This can be helpful to show progress when generating
movies with ``off_screen=True``.
Examples
--------
Plot an orbit around the earth. Save the gif as a temporary file.
>>> from pathlib import Path
>>> from tempfile import mkdtemp
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.load_globe()
>>> texture = examples.load_globe_texture()
>>> filename = Path(mkdtemp()) / 'orbit.gif'
>>> plotter = pv.Plotter(window_size=[300, 300])
>>> _ = plotter.add_mesh(
... mesh, texture=texture, smooth_shading=True
... )
>>> plotter.open_gif(filename)
>>> viewup = [0, 0, 1]
>>> orbit = plotter.generate_orbital_path(
... factor=2.0, n_points=24, shift=0.0, viewup=viewup
... )
>>> plotter.orbit_on_path(
... orbit, write_frames=True, viewup=viewup, step=0.02
... )
See :ref:`orbiting_example` for a full example using this method.
"""
if focus is None:
focus = self.center
if viewup is None:
viewup = self._theme.camera.viewup
if path is None:
path = self.generate_orbital_path(viewup=viewup)
if not is_pyvista_dataset(path):
path = pyvista.PolyData(path)
points = path.points
# Make sure the whole scene is visible
self.camera.thickness = path.length
if progress_bar:
try:
from tqdm import tqdm
except ImportError: # pragma: no cover
raise ImportError("Please install `tqdm` to use ``progress_bar=True``")
def orbit():
"""Define the internal thread for running the orbit."""
points_seq = tqdm(points) if progress_bar else points
for point in points_seq:
tstart = time.time() # include the render time in the step time
self.set_position(point, render=False)
self.set_focus(focus, render=False)
self.set_viewup(viewup, render=False)
self.renderer.ResetCameraClippingRange()
if write_frames:
self.write_frame()
else:
self.render()
sleep_time = step - (time.time() - tstart)
if sleep_time > 0 and not self.off_screen:
time.sleep(sleep_time)
if write_frames:
self.mwriter.close()
if threaded:
thread = Thread(target=orbit)
thread.start()
else:
orbit()
def export_obj(self, filename):
"""Export scene to OBJ format.
Parameters
----------
filename : str | Path
Filename to export the scene to. Must end in ``'.obj'``.
Examples
--------
Export the scene to "scene.obj"
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.export_obj('scene.obj') # doctest:+SKIP
"""
from vtkmodules.vtkIOExport import vtkOBJExporter
if self.render_window is None:
raise RuntimeError("This plotter must still have a render window open.")
if (
isinstance(pyvista.FIGURE_PATH, str) and not Path(filename).is_absolute()
): # pragma: no cover
filename = Path(pyvista.FIGURE_PATH) / filename
else:
filename = Path(filename).expanduser().resolve()
if not filename.suffix == '.obj':
raise ValueError('`filename` must end with ".obj"')
exporter = vtkOBJExporter()
# remove the extension as VTK always adds it in
if pyvista.vtk_version_info < (9, 2, 2): # pragma no cover
exporter.SetFilePrefix(str(filename.with_suffix('')))
else:
exporter.SetFilePrefix(filename.with_suffix(''))
exporter.SetRenderWindow(self.render_window)
exporter.Write()
@property
def _datasets(self):
"""Return a list of all datasets associated with this plotter."""
datasets = []
for renderer in self.renderers:
for actor in renderer.actors.values():
mapper = actor.GetMapper()
# ignore any mappers whose inputs are not datasets
if hasattr(mapper, 'GetInputAsDataSet'):
datasets.append(wrap(mapper.GetInputAsDataSet()))
return datasets
def __del__(self):
"""Delete the plotter."""
# We have to check here if the plotter was only partially initialized
if self._initialized:
if not self._closed:
self.close()
self.deep_clean()
if self._initialized:
del self.renderers
def add_background_image(self, image_path, scale=1.0, auto_resize=True, as_global=True):
"""Add a background image to a plot.
Parameters
----------
image_path : str
Path to an image file.
scale : float, default: 1.0
Scale the image larger or smaller relative to the size of
the window. For example, a scale size of 2 will make the
largest dimension of the image twice as large as the
largest dimension of the render window.
auto_resize : bool, default: True
Resize the background when the render window changes size.
as_global : bool, default: True
When multiple render windows are present, setting
``as_global=False`` will cause the background to only
appear in one window.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(pv.Sphere())
>>> plotter.add_background_image(examples.mapfile)
>>> plotter.show()
"""
if self.renderers.has_active_background_renderer:
raise RuntimeError(
'A background image already exists. '
'Remove it with ``remove_background_image`` '
'before adding one',
)
# Need to change the number of layers to support an additional
# background layer
if not self._has_background_layer:
self.render_window.SetNumberOfLayers(3)
renderer = self.renderers.add_background_renderer(image_path, scale, as_global)
self.render_window.AddRenderer(renderer)
# set up autoscaling of the image
if auto_resize: # pragma: no cover
self.iren.add_observer('ModifiedEvent', renderer.resize)
@wraps(Renderers.remove_background_image)
def remove_background_image(self): # numpydoc ignore=PR01,RT01
"""Wrap ``Renderers.remove_background_image``."""
self.renderers.remove_background_image()
# return the active renderer to the top, otherwise flat background
# will not be rendered
self.renderer.layer = 0
def _on_first_render_request(self):
"""Once an image or render is officially requested, run this routine.
For example on the show call or any screenshot producing code.
"""
# reset unless camera for the first render unless camera is set
if self._first_time:
for renderer in self.renderers:
if not renderer.camera.is_set:
renderer.camera_position = renderer.get_default_cam_pos()
renderer.ResetCamera()
self._first_time = False
def reset_camera_clipping_range(self):
"""Reset camera clipping planes."""
self.renderer.ResetCameraClippingRange()
def add_light(self, light, only_active=False):
"""Add a Light to the scene.
Parameters
----------
light : Light or vtkLight
The light to be added.
only_active : bool, default: False
If ``True``, only add the light to the active
renderer. The default is that every renderer adds the
light. To add the light to an arbitrary renderer, see
:func:`pyvista.Renderer.add_light`.
Examples
--------
Create a plotter that we initialize with no lights, and add a
cube and a single headlight to it.
>>> import pyvista as pv
>>> plotter = pv.Plotter(lighting='none')
>>> _ = plotter.add_mesh(pv.Cube())
>>> light = pv.Light(color='cyan', light_type='headlight')
>>> plotter.add_light(light)
>>> plotter.show()
"""
renderers = [self.renderer] if only_active else self.renderers
for renderer in renderers:
renderer.add_light(light)
def remove_all_lights(self, only_active=False):
"""Remove all lights from the scene.
Parameters
----------
only_active : bool, default: False
If ``True``, only remove lights from the active
renderer. The default is that lights are stripped from
every renderer.
Examples
--------
Create a plotter and remove all lights after initialization.
Note how the mesh rendered is completely flat
>>> import pyvista as pv
>>> plotter = pv.Plotter()
>>> plotter.remove_all_lights()
>>> plotter.renderer.lights
[]
>>> _ = plotter.add_mesh(pv.Sphere(), show_edges=True)
>>> plotter.show()
Note how this differs from a plot with default lighting
>>> pv.Sphere().plot(show_edges=True, lighting=True)
"""
renderers = [self.renderer] if only_active else self.renderers
for renderer in renderers:
renderer.remove_all_lights()
def where_is(self, name):
"""Return the subplot coordinates of a given actor.
Parameters
----------
name : str
Actor's name.
Returns
-------
list[tuple[int, int]]
A list with the subplot coordinates of the actor.
Examples
--------
>>> import pyvista as pv
>>> plotter = pv.Plotter(shape=(2, 2))
>>> plotter.subplot(0, 0)
>>> _ = plotter.add_mesh(pv.Box(), name='box')
>>> plotter.subplot(0, 1)
>>> _ = plotter.add_mesh(pv.Sphere(), name='sphere')
>>> plotter.subplot(1, 0)
>>> _ = plotter.add_mesh(pv.Box(), name='box')
>>> plotter.subplot(1, 1)
>>> _ = plotter.add_mesh(pv.Cone(), name='cone')
>>> plotter.where_is('box')
[(0, 0), (1, 0)]
>>> plotter.show()
"""
return [
tuple(self.renderers.index_to_loc(index).tolist())
for index in range(len(self.renderers))
if name in self.renderers[index]._actors
]
class Plotter(BasePlotter):
"""Plotting object to display vtk meshes or numpy arrays.
Parameters
----------
off_screen : bool, optional
Renders off screen when ``True``. Useful for automated
screenshots.
notebook : bool, optional
When ``True``, the resulting plot is placed inline a jupyter
notebook. Assumes a jupyter console is active. Automatically
enables ``off_screen``.
shape : sequence[int], optional
Number of sub-render windows inside of the main window.
Specify two across with ``shape=(2, 1)`` and a two by two grid
with ``shape=(2, 2)``. By default there is only one render
window. Can also accept a string descriptor as shape. E.g.:
* ``shape="3|1"`` means 3 plots on the left and 1 on the right,
* ``shape="4/2"`` means 4 plots on top and 2 at the bottom.
border : bool, optional
Draw a border around each render window.
border_color : ColorLike, default: "k"
Either a string, rgb list, or hex color string. For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
window_size : sequence[int], optional
Window size in pixels. Defaults to ``[1024, 768]``, unless
set differently in the relevant theme's ``window_size``
property.
line_smoothing : bool, default: False
If ``True``, enable line smoothing.
polygon_smoothing : bool, default: False
If ``True``, enable polygon smoothing.
lighting : str, default: 'light kit"
Lighting to set up for the plotter. Accepted options:
* ``'light kit'``: a vtk Light Kit composed of 5 lights.
* ``'three lights'``: illumination using 3 lights.
* ``'none'``: no light sources at instantiation.
The default is a ``'light kit'`` (to be precise, 5 separate
lights that act like a Light Kit).
theme : pyvista.plotting.themes.Theme, optional
Plot-specific theme.
image_scale : int, optional
Scale factor when saving screenshots. Image sizes will be
the ``window_size`` multiplied by this scale factor.
Examples
--------
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> another_mesh = pv.Sphere()
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(
... mesh, color='red', style='wireframe', line_width=4
... )
>>> actor = pl.add_mesh(another_mesh, color='blue')
>>> pl.show()
"""
last_update_time = 0.0
def __init__(
self,
off_screen=None,
notebook=None,
shape=(1, 1),
groups=None,
row_weights=None,
col_weights=None,
border=None,
border_color='k',
border_width=2.0,
window_size=None,
line_smoothing=False,
point_smoothing=False,
polygon_smoothing=False,
splitting_position=None,
title=None,
lighting='light kit',
theme=None,
image_scale=None,
):
"""Initialize a vtk plotting object."""
super().__init__(
shape=shape,
border=border,
border_color=border_color,
border_width=border_width,
groups=groups,
row_weights=row_weights,
col_weights=col_weights,
splitting_position=splitting_position,
title=title,
lighting=lighting,
theme=theme,
image_scale=image_scale,
)
# reset partial initialization flag
self._initialized = False
log.debug('Plotter init start')
# check if a plotting backend is enabled
_warn_xserver()
if off_screen is None:
off_screen = pyvista.OFF_SCREEN
if notebook is None:
if self._theme.notebook is not None:
notebook = self._theme.notebook
else:
notebook = scooby.in_ipykernel()
self.notebook = notebook
if self.notebook or pyvista.ON_SCREENSHOT:
off_screen = True
self.off_screen = off_screen
# initialize render window
self.ren_win = _vtk.vtkRenderWindow()
self.render_window.SetMultiSamples(0)
self.render_window.SetBorders(True)
if line_smoothing:
self.render_window.LineSmoothingOn()
if point_smoothing:
self.render_window.PointSmoothingOn()
if polygon_smoothing:
self.render_window.PolygonSmoothingOn()
for renderer in self.renderers:
self.render_window.AddRenderer(renderer)
# Add the shadow renderer to allow us to capture interactions within
# a given viewport
# https://vtk.org/pipermail/vtkusers/2018-June/102030.html
number_or_layers = self.render_window.GetNumberOfLayers()
current_layer = self.renderer.GetLayer()
self.render_window.SetNumberOfLayers(number_or_layers + 1)
self.render_window.AddRenderer(self.renderers.shadow_renderer)
self.renderers.shadow_renderer.SetLayer(current_layer + 1)
self.renderers.shadow_renderer.SetInteractive(False) # never needs to capture
if self.off_screen:
self.render_window.SetOffScreenRendering(1)
# vtkGenericRenderWindowInteractor has no event loop and
# allows the display client to close on Linux when
# off_screen. We still want an interactor for off screen
# plotting since there are some widgets (like the axes
# widget) that need an interactor
interactor = _vtk.vtkGenericRenderWindowInteractor()
else:
interactor = None
# Add ren win and interactor
self.iren = RenderWindowInteractor(self, light_follow_camera=False, interactor=interactor)
self.iren.set_render_window(self.render_window)
self.reset_key_events()
self.enable_trackball_style() # internally calls update_style()
self.iren.add_observer("KeyPressEvent", self.key_press_event)
# Set camera widget based on theme. This requires that an
# interactor be present.
if self.theme._enable_camera_orientation_widget:
self.add_camera_orientation_widget()
# Set background
self.set_background(self._theme.background)
# Set window size
self._window_size_unset = False
if window_size is None:
self.window_size = self._theme.window_size
if self.window_size == pyvista.plotting.themes.Theme().window_size:
self._window_size_unset = True
else:
self.window_size = window_size
if self._theme.depth_peeling.enabled:
if self.enable_depth_peeling():
for renderer in self.renderers:
renderer.enable_depth_peeling()
# set anti_aliasing based on theme
if self.theme.anti_aliasing:
self.enable_anti_aliasing(self.theme.anti_aliasing)
if self.theme.camera.parallel_projection:
self.enable_parallel_projection()
self.parallel_scale = self.theme.camera.parallel_scale
# some cleanup only necessary for fully initialized plotters
self._initialized = True
log.debug('Plotter init stop')
def show(
self,
title=None,
window_size=None,
interactive=True,
auto_close=None,
interactive_update=False,
full_screen=None,
screenshot=False,
return_img=False,
cpos=None,
jupyter_backend=None,
return_viewer=False,
return_cpos=None,
before_close_callback=None,
**kwargs,
):
"""Display the plotting window.
Parameters
----------
title : str, optional
Title of plotting window. Defaults to
:attr:`pyvista.global_theme.title <pyvista.plotting.themes.Theme.title>`.
window_size : list, optional
Window size in pixels. Defaults to
:attr:`pyvista.global_theme.window_size <pyvista.plotting.themes.Theme.window_size>`.
interactive : bool, optional
Enabled by default. Allows user to pan and move figure.
Defaults to
:attr:`pyvista.global_theme.interactive <pyvista.plotting.themes.Theme.interactive>`.
auto_close : bool, optional
Exits plotting session when user closes the window when
interactive is ``True``. Defaults to
:attr:`pyvista.global_theme.auto_close <pyvista.plotting.themes.Theme.auto_close>`.
interactive_update : bool, default: False
Allows user to non-blocking draw, user should call
:func:`Plotter.update` in each iteration.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores
``window_size``. Defaults to
:attr:`pyvista.global_theme.full_screen <pyvista.plotting.themes.Theme.full_screen>`.
screenshot : str | Path | io.BytesIO | bool, default: False
Take a screenshot of the initial state of the plot. If a string,
it specifies the path to which the screenshot is saved. If
``True``, the screenshot is returned as an array. For interactive
screenshots it's recommended to first call ``show()`` with
``auto_close=False`` to set the scene, then save the screenshot in
a separate call to ``show()`` or :func:`Plotter.screenshot`.
See also the ``before_close_callback`` parameter for an
alternative.
return_img : bool, default: False
Returns a numpy array representing the last image along
with the camera position.
cpos : sequence[sequence[float]], optional
The camera position. You can also set this with
:attr:`Plotter.camera_position`.
jupyter_backend : str, optional
Jupyter notebook plotting backend to use. One of the
following:
* ``'none'`` : Do not display in the notebook.
* ``'static'`` : Display a static figure.
* ``'trame'`` : Display a dynamic figure with Trame.
* ``'html'`` : Use an ebeddable HTML scene.
This can also be set globally with
:func:`pyvista.set_jupyter_backend`.
A dictionary ``jupyter_kwargs`` can also be passed to further
configure how the backend displays.
return_viewer : bool, default: False
Return the jupyterlab viewer, scene, or display object when
plotting with Jupyter notebook. When ``False`` and within a Jupyter
environment, the scene will be immediately shown within the
notebook. Set this to ``True`` to return the scene instead.
return_cpos : bool, optional
Return the last camera position from the render window
when enabled. Default based on theme setting. See
:attr:`pyvista.plotting.themes.Theme.return_cpos`.
before_close_callback : Callable, optional
Callback that is called before the plotter is closed.
The function takes a single parameter, which is the plotter object
before it closes. An example of use is to capture a screenshot after
interaction::
def fun(plotter):
plotter.screenshot('file.png')
**kwargs : dict, optional
Developer keyword arguments.
Returns
-------
cpos : list
List of camera position, focal point, and view up.
Returned only when ``return_cpos=True`` or set in the
default global or plot theme.
image : np.ndarray
Numpy array of the last image when either ``return_img=True``
or ``screenshot=True`` is set. Optionally contains alpha
values. Sized:
* [Window height x Window width x 3] if the theme sets
``transparent_background=False``.
* [Window height x Window width x 4] if the theme sets
``transparent_background=True``.
widget : ipywidgets.Widget
IPython widget when ``return_viewer=True``.
Notes
-----
Please use the ``q``-key to close the plotter as some
operating systems (namely Windows) will experience issues
saving a screenshot if the exit button in the GUI is pressed.
Examples
--------
Simply show the plot of a mesh.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.show()
Take a screenshot interactively. Screenshot will be of the
first image shown, so use the first call with
``auto_close=False`` to set the scene before taking the
screenshot.
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Cube())
>>> pl.show(auto_close=False) # doctest:+SKIP
>>> pl.show(screenshot='my_image.png') # doctest:+SKIP
Obtain the camera position when using ``show``.
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.show(return_cpos=True) # doctest:+SKIP
[(2.223005211686484, -0.3126909484828709, 2.4686209867735065),
(0.0, 0.0, 0.0),
(-0.6839951597283509, -0.47207319712073137, 0.5561452310578585)]
"""
jupyter_kwargs = kwargs.pop('jupyter_kwargs', {})
assert_empty_kwargs(**kwargs)
if before_close_callback is None:
before_close_callback = pyvista.global_theme._before_close_callback
self._before_close_callback = before_close_callback
if interactive_update and auto_close is None:
auto_close = False
elif interactive_update and auto_close:
warnings.warn(
textwrap.dedent(
"""
The plotter will close immediately automatically since ``auto_close=True``.
Either, do not specify ``auto_close``, or set it to ``False`` if you want to
interact with the plotter interactively.
""",
).strip(),
)
elif auto_close is None:
auto_close = self._theme.auto_close
if self.render_window is None:
raise RuntimeError("This plotter has been closed and cannot be shown.")
if full_screen is None:
full_screen = self._theme.full_screen
if full_screen:
self.render_window.SetFullScreen(True)
self.render_window.BordersOn() # super buggy when disabled
else:
if window_size is None:
window_size = self.window_size
else:
self._window_size_unset = False
self.render_window.SetSize(window_size[0], window_size[1])
# reset unless camera for the first render unless camera is set
self.camera_position = cpos
self._on_first_render_request()
# handle plotter notebook
if jupyter_backend and not self.notebook:
warnings.warn(
'Not within a jupyter notebook environment.\nIgnoring ``jupyter_backend``.',
)
jupyter_disp = None
if self.notebook:
from pyvista.jupyter.notebook import handle_plotter
if jupyter_backend is None:
jupyter_backend = self._theme.jupyter_backend
if jupyter_backend.lower() != 'none':
jupyter_disp = handle_plotter(self, backend=jupyter_backend, **jupyter_kwargs)
self.render()
# initial double render needed for certain passes when offscreen
if self.off_screen and 'vtkDepthOfFieldPass' in self.renderer._render_passes._passes:
self.render()
# This has to be after the first render for some reason
if title is None:
title = self.title
if title:
self.render_window.SetWindowName(title)
self.title = title
# Keep track of image for sphinx-gallery
if pyvista.BUILDING_GALLERY:
# always save screenshots for sphinx_gallery
self.last_image = self.screenshot(screenshot, return_img=True)
self.last_image_depth = self.get_image_depth()
with suppress(ImportError):
self.last_vtksz = self.export_vtksz(filename=None)
# See: https://github.com/pyvista/pyvista/issues/186#issuecomment-550993270
if interactive and not self.off_screen:
try: # interrupts will be caught here
log.debug('Starting iren')
self.iren.update_style()
if not interactive_update:
# Resolves #1260
if os.name == 'nt': # pragma: no cover
self.iren.process_events()
self.iren.start()
if pyvista.vtk_version_info < (9, 2, 3): # pragma: no cover
self.iren.initialize()
except KeyboardInterrupt:
log.debug('KeyboardInterrupt')
self.close()
raise KeyboardInterrupt
# In the event that the user hits the exit-button on the GUI (on
# Windows OS) then it must be finalized and deleted as accessing it
# will kill the kernel.
# Here we check for that and clean it up before moving on to any of
# the closing routines that might try to still access that
# render window.
# Ignore if using a Jupyter display
_is_current = self.render_window.IsCurrent()
if jupyter_disp is None and not _is_current:
self._clear_ren_win() # The ren_win is deleted
# proper screenshots cannot be saved if this happens
if not auto_close:
warnings.warn(
"`auto_close` ignored: by clicking the exit button, "
"you have destroyed the render window and we have to "
"close it out.",
)
self.close()
if screenshot:
warnings.warn(
"A screenshot is unable to be taken as the render window is not current or rendering is suppressed.",
)
if _is_current:
if pyvista.ON_SCREENSHOT:
filename = uuid.uuid4().hex
self.last_image = self.screenshot(filename, return_img=True)
else:
self.last_image = self.screenshot(screenshot, return_img=True)
self.last_image_depth = self.get_image_depth()
# NOTE: after this point, nothing from the render window can be accessed
# as if a user pressed the close button, then it destroys the
# the render view and a stream of errors will kill the Python
# kernel if code here tries to access that renderer.
# See issues #135 and #186 for insight before editing the
# remainder of this function.
# Close the render window if requested
if jupyter_disp is None and auto_close:
# Plotters are never auto-closed in Jupyter
self.close()
if jupyter_disp is not None and not return_viewer:
# Default behaviour is to display the Jupyter viewer
try:
from IPython import display
except ImportError: # pragma: no cover
raise ImportError('Install IPython to display an image in a notebook')
display.display(jupyter_disp)
# Three possible return values: (cpos, image, widget)
return_values = tuple(
val
for val in (
self.camera_position if return_cpos else None,
self.last_image if return_img or screenshot is True else None,
jupyter_disp if return_viewer else None,
)
if val is not None
)
if len(return_values) == 1:
return return_values[0]
return return_values or None
def add_title(self, title, font_size=18, color=None, font=None, shadow=False):
"""Add text to the top center of the plot.
This is merely a convenience method that calls ``add_text``
with ``position='upper_edge'``.
Parameters
----------
title : str
The text to add the rendering.
font_size : float, default: 18
Sets the size of the title font.
color : ColorLike, optional
Either a string, rgb list, or hex color string. Defaults
to white or the value of the global theme if set. For
example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
font : str, optional
Font name may be ``'courier'``, ``'times'``, or ``'arial'``.
shadow : bool, default: False
Adds a black shadow to the text.
Returns
-------
vtk.vtkTextActor
Text actor added to plot.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.background_color = 'grey'
>>> actor = pl.add_title(
... 'Plot Title', font='courier', color='k', font_size=40
... )
>>> pl.show()
"""
# add additional spacing from the top of the figure by default
title = '\n' + title
return self.add_text(
title,
position='upper_edge',
font_size=font_size,
color=color,
font=font,
shadow=shadow,
name='title',
viewport=False,
)
def add_cursor(
self,
bounds=(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
focal_point=(0.0, 0.0, 0.0),
color=None,
):
"""Add a cursor of a PyVista or VTK dataset to the scene.
Parameters
----------
bounds : sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
Specify the bounds in the format of:
- ``(xmin, xmax, ymin, ymax, zmin, zmax)``
focal_point : sequence[float], default: (0.0, 0.0, 0.0)
The focal point of the cursor.
color : ColorLike, optional
Either a string, RGB sequence, or hex color string. For one
of the following.
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
Returns
-------
vtk.vtkActor
VTK actor of the 2D cursor.
Examples
--------
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere)
>>> _ = plotter.add_cursor()
>>> plotter.show()
"""
alg = _vtk.vtkCursor3D()
alg.SetModelBounds(bounds)
alg.SetFocalPoint(focal_point)
alg.AllOn()
mapper = DataSetMapper(theme=self._theme)
mapper.SetInputConnection(alg.GetOutputPort())
actor, prop = self.add_actor(mapper)
prop.SetColor(Color(color).float_rgb)
return actor
@property
def meshes(self): # numpydoc ignore=RT01
"""Return plotter meshes.
Returns
-------
list[pyvista.DataSet | pyvista.MultiBlock]
List of mesh objects such as pyvista.PolyData, pyvista.UnstructuredGrid, etc.
"""
return [actor.mapper.dataset for actor in self.actors.values() if hasattr(actor, 'mapper')]
# Tracks created plotters. This is the end of the module as we need to
# define ``BasePlotter`` before including it in the type definition.
#
# When pyvista.BUILDING_GALLERY = False, the objects will be ProxyType, and
# when True, BasePlotter.
_ALL_PLOTTERS: dict[str, BasePlotter] = {}
def _kill_display(disp_id): # pragma: no cover
"""Forcibly close the display on Linux.
See: https://gitlab.kitware.com/vtk/vtk/-/issues/17917#note_783584
And more details into why...
https://stackoverflow.com/questions/64811503
Notes
-----
This is to be used experimentally and is known to cause issues
on `pyvistaqt`
"""
if platform.system() != 'Linux':
raise OSError('This method only works on Linux')
if disp_id:
cdisp_id = int(disp_id[1:].split('_')[0], 16)
# this is unsafe as events might be queued, but sometimes the
# window fails to close if we don't just close it
Thread(target=X11.XCloseDisplay, args=(cdisp_id,)).start()
|