Spaces:
Sleeping
Sleeping
File size: 168,384 Bytes
6a86ad5 |
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 |
"""
This module defines tensors with abstract index notation.
The abstract index notation has been first formalized by Penrose.
Tensor indices are formal objects, with a tensor type; there is no
notion of index range, it is only possible to assign the dimension,
used to trace the Kronecker delta; the dimension can be a Symbol.
The Einstein summation convention is used.
The covariant indices are indicated with a minus sign in front of the index.
For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c``
contracted.
A tensor expression ``t`` can be called; called with its
indices in sorted order it is equal to itself:
in the above example ``t(a, b) == t``;
one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``.
The contracted indices are dummy indices, internally they have no name,
the indices being represented by a graph-like structure.
Tensors are put in canonical form using ``canon_bp``, which uses
the Butler-Portugal algorithm for canonicalization using the monoterm
symmetries of the tensors.
If there is a (anti)symmetric metric, the indices can be raised and
lowered when the tensor is put in canonical form.
"""
from __future__ import annotations
from typing import Any
from functools import reduce
from math import prod
from abc import abstractmethod, ABC
from collections import defaultdict
import operator
import itertools
from sympy.core.numbers import (Integer, Rational)
from sympy.combinatorics import Permutation
from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \
bsgs_direct_product, canonicalize, riemann_bsgs
from sympy.core import Basic, Expr, sympify, Add, Mul, S
from sympy.core.cache import clear_cache
from sympy.core.containers import Tuple, Dict
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol, symbols
from sympy.core.sympify import CantSympify, _sympify
from sympy.core.operations import AssocOp
from sympy.external.gmpy import SYMPY_INTS
from sympy.matrices import eye
from sympy.utilities.exceptions import (sympy_deprecation_warning,
SymPyDeprecationWarning,
ignore_warnings)
from sympy.utilities.decorator import memoize_property, deprecated
from sympy.utilities.iterables import sift
def deprecate_data():
sympy_deprecation_warning(
"""
The data attribute of TensorIndexType is deprecated. Use The
replace_with_arrays() method instead.
""",
deprecated_since_version="1.4",
active_deprecations_target="deprecated-tensorindextype-attrs",
stacklevel=4,
)
def deprecate_fun_eval():
sympy_deprecation_warning(
"""
The Tensor.fun_eval() method is deprecated. Use
Tensor.substitute_indices() instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensor-fun-eval",
stacklevel=4,
)
def deprecate_call():
sympy_deprecation_warning(
"""
Calling a tensor like Tensor(*indices) is deprecated. Use
Tensor.substitute_indices() instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensor-fun-eval",
stacklevel=4,
)
class _IndexStructure(CantSympify):
"""
This class handles the indices (free and dummy ones). It contains the
algorithms to manage the dummy indices replacements and contractions of
free indices under multiplications of tensor expressions, as well as stuff
related to canonicalization sorting, getting the permutation of the
expression and so on. It also includes tools to get the ``TensorIndex``
objects corresponding to the given index structure.
"""
def __init__(self, free, dum, index_types, indices, canon_bp=False):
self.free = free
self.dum = dum
self.index_types = index_types
self.indices = indices
self._ext_rank = len(self.free) + 2*len(self.dum)
self.dum.sort(key=lambda x: x[0])
@staticmethod
def from_indices(*indices):
"""
Create a new ``_IndexStructure`` object from a list of ``indices``.
Explanation
===========
``indices`` ``TensorIndex`` objects, the indices. Contractions are
detected upon construction.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
>>> _IndexStructure.from_indices(m0, m1, -m1, m3)
_IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz])
"""
free, dum = _IndexStructure._free_dum_from_indices(*indices)
index_types = [i.tensor_index_type for i in indices]
indices = _IndexStructure._replace_dummy_names(indices, free, dum)
return _IndexStructure(free, dum, index_types, indices)
@staticmethod
def from_components_free_dum(components, free, dum):
index_types = []
for component in components:
index_types.extend(component.index_types)
indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types)
return _IndexStructure(free, dum, index_types, indices)
@staticmethod
def _free_dum_from_indices(*indices):
"""
Convert ``indices`` into ``free``, ``dum`` for single component tensor.
Explanation
===========
``free`` list of tuples ``(index, pos, 0)``,
where ``pos`` is the position of index in
the list of indices formed by the component tensors
``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)``
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \
_IndexStructure
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
>>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3)
([(m0, 0), (m3, 3)], [(1, 2)])
"""
n = len(indices)
if n == 1:
return [(indices[0], 0)], []
# find the positions of the free indices and of the dummy indices
free = [True]*len(indices)
index_dict = {}
dum = []
for i, index in enumerate(indices):
name = index.name
typ = index.tensor_index_type
contr = index.is_up
if (name, typ) in index_dict:
# found a pair of dummy indices
is_contr, pos = index_dict[(name, typ)]
# check consistency and update free
if is_contr:
if contr:
raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i))
else:
free[pos] = False
free[i] = False
else:
if contr:
free[pos] = False
free[i] = False
else:
raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i))
if contr:
dum.append((i, pos))
else:
dum.append((pos, i))
else:
index_dict[(name, typ)] = index.is_up, i
free = [(index, i) for i, index in enumerate(indices) if free[i]]
free.sort()
return free, dum
def get_indices(self):
"""
Get a list of indices, creating new tensor indices to complete dummy indices.
"""
return self.indices[:]
@staticmethod
def generate_indices_from_free_dum_index_types(free, dum, index_types):
indices = [None]*(len(free)+2*len(dum))
for idx, pos in free:
indices[pos] = idx
generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
for pos1, pos2 in dum:
typ1 = index_types[pos1]
indname = generate_dummy_name(typ1)
indices[pos1] = TensorIndex(indname, typ1, True)
indices[pos2] = TensorIndex(indname, typ1, False)
return _IndexStructure._replace_dummy_names(indices, free, dum)
@staticmethod
def _get_generator_for_dummy_indices(free):
cdt = defaultdict(int)
# if the free indices have names with dummy_name, start with an
# index higher than those for the dummy indices
# to avoid name collisions
for indx, ipos in free:
if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name:
cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1)
def dummy_name_gen(tensor_index_type):
nd = str(cdt[tensor_index_type])
cdt[tensor_index_type] += 1
return tensor_index_type.dummy_name + '_' + nd
return dummy_name_gen
@staticmethod
def _replace_dummy_names(indices, free, dum):
dum.sort(key=lambda x: x[0])
new_indices = list(indices)
assert len(indices) == len(free) + 2*len(dum)
generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
for ipos1, ipos2 in dum:
typ1 = new_indices[ipos1].tensor_index_type
indname = generate_dummy_name(typ1)
new_indices[ipos1] = TensorIndex(indname, typ1, True)
new_indices[ipos2] = TensorIndex(indname, typ1, False)
return new_indices
def get_free_indices(self) -> list[TensorIndex]:
"""
Get a list of free indices.
"""
# get sorted indices according to their position:
free = sorted(self.free, key=lambda x: x[1])
return [i[0] for i in free]
def __str__(self):
return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types)
def __repr__(self):
return self.__str__()
def _get_sorted_free_indices_for_canon(self):
sorted_free = self.free[:]
sorted_free.sort(key=lambda x: x[0])
return sorted_free
def _get_sorted_dum_indices_for_canon(self):
return sorted(self.dum, key=lambda x: x[0])
def _get_lexicographically_sorted_index_types(self):
permutation = self.indices_canon_args()[0]
index_types = [None]*self._ext_rank
for i, it in enumerate(self.index_types):
index_types[permutation(i)] = it
return index_types
def _get_lexicographically_sorted_indices(self):
permutation = self.indices_canon_args()[0]
indices = [None]*self._ext_rank
for i, it in enumerate(self.indices):
indices[permutation(i)] = it
return indices
def perm2tensor(self, g, is_canon_bp=False):
"""
Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``.
Explanation
===========
``g`` permutation corresponding to the tensor in the representation
used in canonicalization
``is_canon_bp`` if True, then ``g`` is the permutation
corresponding to the canonical form of the tensor
"""
sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()]
lex_index_types = self._get_lexicographically_sorted_index_types()
lex_indices = self._get_lexicographically_sorted_indices()
nfree = len(sorted_free)
rank = self._ext_rank
dum = [[None]*2 for i in range((rank - nfree)//2)]
free = []
index_types = [None]*rank
indices = [None]*rank
for i in range(rank):
gi = g[i]
index_types[i] = lex_index_types[gi]
indices[i] = lex_indices[gi]
if gi < nfree:
ind = sorted_free[gi]
assert index_types[i] == sorted_free[gi].tensor_index_type
free.append((ind, i))
else:
j = gi - nfree
idum, cov = divmod(j, 2)
if cov:
dum[idum][1] = i
else:
dum[idum][0] = i
dum = [tuple(x) for x in dum]
return _IndexStructure(free, dum, index_types, indices)
def indices_canon_args(self):
"""
Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize``
See ``canonicalize`` in ``tensor_can.py`` in combinatorics module.
"""
# to be called after sorted_components
from sympy.combinatorics.permutations import _af_new
n = self._ext_rank
g = [None]*n + [n, n+1]
# Converts the symmetry of the metric into msym from .canonicalize()
# method in the combinatorics module
def metric_symmetry_to_msym(metric):
if metric is None:
return None
sym = metric.symmetry
if sym == TensorSymmetry.fully_symmetric(2):
return 0
if sym == TensorSymmetry.fully_symmetric(-2):
return 1
return None
# ordered indices: first the free indices, ordered by types
# then the dummy indices, ordered by types and contravariant before
# covariant
# g[position in tensor] = position in ordered indices
for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()):
g[ipos] = i
pos = len(self.free)
j = len(self.free)
dummies = []
prev = None
a = []
msym = []
for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon():
g[ipos1] = j
g[ipos2] = j + 1
j += 2
typ = self.index_types[ipos1]
if typ != prev:
if a:
dummies.append(a)
a = [pos, pos + 1]
prev = typ
msym.append(metric_symmetry_to_msym(typ.metric))
else:
a.extend([pos, pos + 1])
pos += 2
if a:
dummies.append(a)
return _af_new(g), dummies, msym
def components_canon_args(components):
numtyp = []
prev = None
for t in components:
if t == prev:
numtyp[-1][1] += 1
else:
prev = t
numtyp.append([prev, 1])
v = []
for h, n in numtyp:
if h.comm in (0, 1):
comm = h.comm
else:
comm = TensorManager.get_comm(h.comm, h.comm)
v.append((h.symmetry.base, h.symmetry.generators, n, comm))
return v
class _TensorDataLazyEvaluator(CantSympify):
"""
EXPERIMENTAL: do not rely on this class, it may change without deprecation
warnings in future versions of SymPy.
Explanation
===========
This object contains the logic to associate components data to a tensor
expression. Components data are set via the ``.data`` property of tensor
expressions, is stored inside this class as a mapping between the tensor
expression and the ``ndarray``.
Computations are executed lazily: whereas the tensor expressions can have
contractions, tensor products, and additions, components data are not
computed until they are accessed by reading the ``.data`` property
associated to the tensor expression.
"""
_substitutions_dict: dict[Any, Any] = {}
_substitutions_dict_tensmul: dict[Any, Any] = {}
def __getitem__(self, key):
dat = self._get(key)
if dat is None:
return None
from .array import NDimArray
if not isinstance(dat, NDimArray):
return dat
if dat.rank() == 0:
return dat[()]
elif dat.rank() == 1 and len(dat) == 1:
return dat[0]
return dat
def _get(self, key):
"""
Retrieve ``data`` associated with ``key``.
Explanation
===========
This algorithm looks into ``self._substitutions_dict`` for all
``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a
TensorHead instance). It reconstructs the components data that the
tensor expression should have by performing on components data the
operations that correspond to the abstract tensor operations applied.
Metric tensor is handled in a different manner: it is pre-computed in
``self._substitutions_dict_tensmul``.
"""
if key in self._substitutions_dict:
return self._substitutions_dict[key]
if isinstance(key, TensorHead):
return None
if isinstance(key, Tensor):
# special case to handle metrics. Metric tensors cannot be
# constructed through contraction by the metric, their
# components show if they are a matrix or its inverse.
signature = tuple([i.is_up for i in key.get_indices()])
srch = (key.component,) + signature
if srch in self._substitutions_dict_tensmul:
return self._substitutions_dict_tensmul[srch]
array_list = [self.data_from_tensor(key)]
return self.data_contract_dum(array_list, key.dum, key.ext_rank)
if isinstance(key, TensMul):
tensmul_args = key.args
if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1:
# special case to handle metrics. Metric tensors cannot be
# constructed through contraction by the metric, their
# components show if they are a matrix or its inverse.
signature = tuple([i.is_up for i in tensmul_args[0].get_indices()])
srch = (tensmul_args[0].components[0],) + signature
if srch in self._substitutions_dict_tensmul:
return self._substitutions_dict_tensmul[srch]
#data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)]
data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)]
coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)])
if all(i is None for i in data_list):
return None
if any(i is None for i in data_list):
raise ValueError("Mixing tensors with associated components "\
"data with tensors without components data")
data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank)
return coeff*data_result
if isinstance(key, TensAdd):
data_list = []
free_args_list = []
for arg in key.args:
if isinstance(arg, TensExpr):
data_list.append(arg.data)
free_args_list.append([x[0] for x in arg.free])
else:
data_list.append(arg)
free_args_list.append([])
if all(i is None for i in data_list):
return None
if any(i is None for i in data_list):
raise ValueError("Mixing tensors with associated components "\
"data with tensors without components data")
sum_list = []
from .array import permutedims
for data, free_args in zip(data_list, free_args_list):
if len(free_args) < 2:
sum_list.append(data)
else:
free_args_pos = {y: x for x, y in enumerate(free_args)}
axes = [free_args_pos[arg] for arg in key.free_args]
sum_list.append(permutedims(data, axes))
return reduce(lambda x, y: x+y, sum_list)
return None
@staticmethod
def data_contract_dum(ndarray_list, dum, ext_rank):
from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray
arrays = list(map(MutableDenseNDimArray, ndarray_list))
prodarr = tensorproduct(*arrays)
return tensorcontraction(prodarr, *dum)
def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead):
"""
This method is used when assigning components data to a ``TensMul``
object, it converts components data to a fully contravariant ndarray,
which is then stored according to the ``TensorHead`` key.
"""
if data is None:
return None
return self._correct_signature_from_indices(
data,
tensmul.get_indices(),
tensmul.free,
tensmul.dum,
True)
def data_from_tensor(self, tensor):
"""
This method corrects the components data to the right signature
(covariant/contravariant) using the metric associated with each
``TensorIndexType``.
"""
tensorhead = tensor.component
if tensorhead.data is None:
return None
return self._correct_signature_from_indices(
tensorhead.data,
tensor.get_indices(),
tensor.free,
tensor.dum)
def _assign_data_to_tensor_expr(self, key, data):
if isinstance(key, TensAdd):
raise ValueError('cannot assign data to TensAdd')
# here it is assumed that `key` is a `TensMul` instance.
if len(key.components) != 1:
raise ValueError('cannot assign data to TensMul with multiple components')
tensorhead = key.components[0]
newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead)
return tensorhead, newdata
def _check_permutations_on_data(self, tens, data):
from .array import permutedims
from .array.arrayop import Flatten
if isinstance(tens, TensorHead):
rank = tens.rank
generators = tens.symmetry.generators
elif isinstance(tens, Tensor):
rank = tens.rank
generators = tens.components[0].symmetry.generators
elif isinstance(tens, TensorIndexType):
rank = tens.metric.rank
generators = tens.metric.symmetry.generators
# Every generator is a permutation, check that by permuting the array
# by that permutation, the array will be the same, except for a
# possible sign change if the permutation admits it.
for gener in generators:
sign_change = +1 if (gener(rank) == rank) else -1
data_swapped = data
last_data = data
permute_axes = list(map(gener, range(rank)))
# the order of a permutation is the number of times to get the
# identity by applying that permutation.
for i in range(gener.order()-1):
data_swapped = permutedims(data_swapped, permute_axes)
# if any value in the difference array is non-zero, raise an error:
if any(Flatten(last_data - sign_change*data_swapped)):
raise ValueError("Component data symmetry structure error")
last_data = data_swapped
def __setitem__(self, key, value):
"""
Set the components data of a tensor object/expression.
Explanation
===========
Components data are transformed to the all-contravariant form and stored
with the corresponding ``TensorHead`` object. If a ``TensorHead`` object
cannot be uniquely identified, it will raise an error.
"""
data = _TensorDataLazyEvaluator.parse_data(value)
self._check_permutations_on_data(key, data)
# TensorHead and TensorIndexType can be assigned data directly, while
# TensMul must first convert data to a fully contravariant form, and
# assign it to its corresponding TensorHead single component.
if not isinstance(key, (TensorHead, TensorIndexType)):
key, data = self._assign_data_to_tensor_expr(key, data)
if isinstance(key, TensorHead):
for dim, indextype in zip(data.shape, key.index_types):
if indextype.data is None:
raise ValueError("index type {} has no components data"\
" associated (needed to raise/lower index)".format(indextype))
if not indextype.dim.is_number:
continue
if dim != indextype.dim:
raise ValueError("wrong dimension of ndarray")
self._substitutions_dict[key] = data
def __delitem__(self, key):
del self._substitutions_dict[key]
def __contains__(self, key):
return key in self._substitutions_dict
def add_metric_data(self, metric, data):
"""
Assign data to the ``metric`` tensor. The metric tensor behaves in an
anomalous way when raising and lowering indices.
Explanation
===========
A fully covariant metric is the inverse transpose of the fully
contravariant metric (it is meant matrix inverse). If the metric is
symmetric, the transpose is not necessary and mixed
covariant/contravariant metrics are Kronecker deltas.
"""
# hard assignment, data should not be added to `TensorHead` for metric:
# the problem with `TensorHead` is that the metric is anomalous, i.e.
# raising and lowering the index means considering the metric or its
# inverse, this is not the case for other tensors.
self._substitutions_dict_tensmul[metric, True, True] = data
inverse_transpose = self.inverse_transpose_matrix(data)
# in symmetric spaces, the transpose is the same as the original matrix,
# the full covariant metric tensor is the inverse transpose, so this
# code will be able to handle non-symmetric metrics.
self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose
# now mixed cases, these are identical to the unit matrix if the metric
# is symmetric.
m = data.tomatrix()
invt = inverse_transpose.tomatrix()
self._substitutions_dict_tensmul[metric, True, False] = m * invt
self._substitutions_dict_tensmul[metric, False, True] = invt * m
@staticmethod
def _flip_index_by_metric(data, metric, pos):
from .array import tensorproduct, tensorcontraction
mdim = metric.rank()
ddim = data.rank()
if pos == 0:
data = tensorcontraction(
tensorproduct(
metric,
data
),
(1, mdim+pos)
)
else:
data = tensorcontraction(
tensorproduct(
data,
metric
),
(pos, ddim)
)
return data
@staticmethod
def inverse_matrix(ndarray):
m = ndarray.tomatrix().inv()
return _TensorDataLazyEvaluator.parse_data(m)
@staticmethod
def inverse_transpose_matrix(ndarray):
m = ndarray.tomatrix().inv().T
return _TensorDataLazyEvaluator.parse_data(m)
@staticmethod
def _correct_signature_from_indices(data, indices, free, dum, inverse=False):
"""
Utility function to correct the values inside the components data
ndarray according to whether indices are covariant or contravariant.
It uses the metric matrix to lower values of covariant indices.
"""
# change the ndarray values according covariantness/contravariantness of the indices
# use the metric
for i, indx in enumerate(indices):
if not indx.is_up and not inverse:
data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i)
elif not indx.is_up and inverse:
data = _TensorDataLazyEvaluator._flip_index_by_metric(
data,
_TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data),
i
)
return data
@staticmethod
def _sort_data_axes(old, new):
from .array import permutedims
new_data = old.data.copy()
old_free = [i[0] for i in old.free]
new_free = [i[0] for i in new.free]
for i in range(len(new_free)):
for j in range(i, len(old_free)):
if old_free[j] == new_free[i]:
old_free[i], old_free[j] = old_free[j], old_free[i]
new_data = permutedims(new_data, (i, j))
break
return new_data
@staticmethod
def add_rearrange_tensmul_parts(new_tensmul, old_tensmul):
def sorted_compo():
return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul)
_TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo()
@staticmethod
def parse_data(data):
"""
Transform ``data`` to array. The parameter ``data`` may
contain data in various formats, e.g. nested lists, SymPy ``Matrix``,
and so on.
Examples
========
>>> from sympy.tensor.tensor import _TensorDataLazyEvaluator
>>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12])
[1, 3, -6, 12]
>>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]])
[[1, 2], [4, 7]]
"""
from .array import MutableDenseNDimArray
if not isinstance(data, MutableDenseNDimArray):
if len(data) == 2 and hasattr(data[0], '__call__'):
data = MutableDenseNDimArray(data[0], data[1])
else:
data = MutableDenseNDimArray(data)
return data
_tensor_data_substitution_dict = _TensorDataLazyEvaluator()
class _TensorManager:
"""
Class to manage tensor properties.
Notes
=====
Tensors belong to tensor commutation groups; each group has a label
``comm``; there are predefined labels:
``0`` tensors commuting with any other tensor
``1`` tensors anticommuting among themselves
``2`` tensors not commuting, apart with those with ``comm=0``
Other groups can be defined using ``set_comm``; tensors in those
groups commute with those with ``comm=0``; by default they
do not commute with any other group.
"""
def __init__(self):
self._comm_init()
def _comm_init(self):
self._comm = [{} for i in range(3)]
for i in range(3):
self._comm[0][i] = 0
self._comm[i][0] = 0
self._comm[1][1] = 1
self._comm[2][1] = None
self._comm[1][2] = None
self._comm_symbols2i = {0:0, 1:1, 2:2}
self._comm_i2symbol = {0:0, 1:1, 2:2}
@property
def comm(self):
return self._comm
def comm_symbols2i(self, i):
"""
Get the commutation group number corresponding to ``i``.
``i`` can be a symbol or a number or a string.
If ``i`` is not already defined its commutation group number
is set.
"""
if i not in self._comm_symbols2i:
n = len(self._comm)
self._comm.append({})
self._comm[n][0] = 0
self._comm[0][n] = 0
self._comm_symbols2i[i] = n
self._comm_i2symbol[n] = i
return n
return self._comm_symbols2i[i]
def comm_i2symbol(self, i):
"""
Returns the symbol corresponding to the commutation group number.
"""
return self._comm_i2symbol[i]
def set_comm(self, i, j, c):
"""
Set the commutation parameter ``c`` for commutation groups ``i, j``.
Parameters
==========
i, j : symbols representing commutation groups
c : group commutation number
Notes
=====
``i, j`` can be symbols, strings or numbers,
apart from ``0, 1`` and ``2`` which are reserved respectively
for commuting, anticommuting tensors and tensors not commuting
with any other group apart with the commuting tensors.
For the remaining cases, use this method to set the commutation rules;
by default ``c=None``.
The group commutation number ``c`` is assigned in correspondence
to the group commutation symbols; it can be
0 commuting
1 anticommuting
None no commutation property
Examples
========
``G`` and ``GH`` do not commute with themselves and commute with
each other; A is commuting.
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry
>>> Lorentz = TensorIndexType('Lorentz')
>>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz)
>>> A = TensorHead('A', [Lorentz])
>>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
>>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm')
>>> TensorManager.set_comm('Gcomm', 'GHcomm', 0)
>>> (GH(i1)*G(i0)).canon_bp()
G(i0)*GH(i1)
>>> (G(i1)*G(i0)).canon_bp()
G(i1)*G(i0)
>>> (G(i1)*A(i0)).canon_bp()
A(i0)*G(i1)
"""
if c not in (0, 1, None):
raise ValueError('`c` can assume only the values 0, 1 or None')
i = sympify(i)
j = sympify(j)
if i not in self._comm_symbols2i:
n = len(self._comm)
self._comm.append({})
self._comm[n][0] = 0
self._comm[0][n] = 0
self._comm_symbols2i[i] = n
self._comm_i2symbol[n] = i
if j not in self._comm_symbols2i:
n = len(self._comm)
self._comm.append({})
self._comm[0][n] = 0
self._comm[n][0] = 0
self._comm_symbols2i[j] = n
self._comm_i2symbol[n] = j
ni = self._comm_symbols2i[i]
nj = self._comm_symbols2i[j]
self._comm[ni][nj] = c
self._comm[nj][ni] = c
"""
Cached sympy functions (e.g. expand) may have cached the results of
expressions involving tensors, but those results may not be valid after
changing the commutation properties. To stay on the safe side, we clear
the cache of all functions.
"""
clear_cache()
def set_comms(self, *args):
"""
Set the commutation group numbers ``c`` for symbols ``i, j``.
Parameters
==========
args : sequence of ``(i, j, c)``
"""
for i, j, c in args:
self.set_comm(i, j, c)
def get_comm(self, i, j):
"""
Return the commutation parameter for commutation group numbers ``i, j``
see ``_TensorManager.set_comm``
"""
return self._comm[i].get(j, 0 if i == 0 or j == 0 else None)
def clear(self):
"""
Clear the TensorManager.
"""
self._comm_init()
TensorManager = _TensorManager()
class TensorIndexType(Basic):
"""
A TensorIndexType is characterized by its name and its metric.
Parameters
==========
name : name of the tensor type
dummy_name : name of the head of dummy indices
dim : dimension, it can be a symbol or an integer or ``None``
eps_dim : dimension of the epsilon tensor
metric_symmetry : integer that denotes metric symmetry or ``None`` for no metric
metric_name : string with the name of the metric tensor
Attributes
==========
``metric`` : the metric tensor
``delta`` : ``Kronecker delta``
``epsilon`` : the ``Levi-Civita epsilon`` tensor
``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis.
Notes
=====
The possible values of the ``metric_symmetry`` parameter are:
``1`` : metric tensor is fully symmetric
``0`` : metric tensor possesses no index symmetry
``-1`` : metric tensor is fully antisymmetric
``None``: there is no metric tensor (metric equals to ``None``)
The metric is assumed to be symmetric by default. It can also be set
to a custom tensor by the ``.set_metric()`` method.
If there is a metric the metric is used to raise and lower indices.
In the case of non-symmetric metric, the following raising and
lowering conventions will be adopted:
``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)``
From these it is easy to find:
``g(-a, b) = delta(-a, b)``
where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta``
(see ``TensorIndex`` for the conventions on indices).
For antisymmetric metrics there is also the following equality:
``g(a, -b) = -delta(a, -b)``
If there is no metric it is not possible to raise or lower indices;
e.g. the index of the defining representation of ``SU(N)``
is 'covariant' and the conjugate representation is
'contravariant'; for ``N > 2`` they are linearly independent.
``eps_dim`` is by default equal to ``dim``, if the latter is an integer;
else it can be assigned (for use in naive dimensional regularization);
if ``eps_dim`` is not an integer ``epsilon`` is ``None``.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> Lorentz.metric
metric(Lorentz,Lorentz)
"""
def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None,
metric_symmetry=1, metric_name='metric', **kwargs):
if 'dummy_fmt' in kwargs:
dummy_fmt = kwargs['dummy_fmt']
sympy_deprecation_warning(
f"""
The dummy_fmt keyword to TensorIndexType is deprecated. Use
dummy_name={dummy_fmt} instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensorindextype-dummy-fmt",
)
dummy_name = dummy_fmt
if isinstance(name, str):
name = Symbol(name)
if dummy_name is None:
dummy_name = str(name)[0]
if isinstance(dummy_name, str):
dummy_name = Symbol(dummy_name)
if dim is None:
dim = Symbol("dim_" + dummy_name.name)
else:
dim = sympify(dim)
if eps_dim is None:
eps_dim = dim
else:
eps_dim = sympify(eps_dim)
metric_symmetry = sympify(metric_symmetry)
if isinstance(metric_name, str):
metric_name = Symbol(metric_name)
if 'metric' in kwargs:
SymPyDeprecationWarning(
"""
The 'metric' keyword argument to TensorIndexType is
deprecated. Use the 'metric_symmetry' keyword argument or the
TensorIndexType.set_metric() method instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensorindextype-metric",
)
metric = kwargs.get('metric')
if metric is not None:
if metric in (True, False, 0, 1):
metric_name = 'metric'
#metric_antisym = metric
else:
metric_name = metric.name
#metric_antisym = metric.antisym
if metric:
metric_symmetry = -1
else:
metric_symmetry = 1
obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim,
metric_symmetry, metric_name)
obj._autogenerated = []
return obj
@property
def name(self):
return self.args[0].name
@property
def dummy_name(self):
return self.args[1].name
@property
def dim(self):
return self.args[2]
@property
def eps_dim(self):
return self.args[3]
@memoize_property
def metric(self):
metric_symmetry = self.args[4]
metric_name = self.args[5]
if metric_symmetry is None:
return None
if metric_symmetry == 0:
symmetry = TensorSymmetry.no_symmetry(2)
elif metric_symmetry == 1:
symmetry = TensorSymmetry.fully_symmetric(2)
elif metric_symmetry == -1:
symmetry = TensorSymmetry.fully_symmetric(-2)
return TensorHead(metric_name, [self]*2, symmetry)
@memoize_property
def delta(self):
return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2))
@memoize_property
def epsilon(self):
if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)):
return None
symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim)
return TensorHead('Eps', [self]*self.eps_dim, symmetry)
def set_metric(self, tensor):
self._metric = tensor
def __lt__(self, other):
return self.name < other.name
def __str__(self):
return self.name
__repr__ = __str__
# Everything below this line is deprecated
@property
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return _tensor_data_substitution_dict[self]
@data.setter
def data(self, data):
deprecate_data()
# This assignment is a bit controversial, should metric components be assigned
# to the metric only or also to the TensorIndexType object? The advantage here
# is the ability to assign a 1D array and transform it to a 2D diagonal array.
from .array import MutableDenseNDimArray
data = _TensorDataLazyEvaluator.parse_data(data)
if data.rank() > 2:
raise ValueError("data have to be of rank 1 (diagonal metric) or 2.")
if data.rank() == 1:
if self.dim.is_number:
nda_dim = data.shape[0]
if nda_dim != self.dim:
raise ValueError("Dimension mismatch")
dim = data.shape[0]
newndarray = MutableDenseNDimArray.zeros(dim, dim)
for i, val in enumerate(data):
newndarray[i, i] = val
data = newndarray
dim1, dim2 = data.shape
if dim1 != dim2:
raise ValueError("Non-square matrix tensor.")
if self.dim.is_number:
if self.dim != dim1:
raise ValueError("Dimension mismatch")
_tensor_data_substitution_dict[self] = data
_tensor_data_substitution_dict.add_metric_data(self.metric, data)
with ignore_warnings(SymPyDeprecationWarning):
delta = self.get_kronecker_delta()
i1 = TensorIndex('i1', self)
i2 = TensorIndex('i2', self)
with ignore_warnings(SymPyDeprecationWarning):
delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1))
@data.deleter
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if self in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self]
if self.metric in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self.metric]
@deprecated(
"""
The TensorIndexType.get_kronecker_delta() method is deprecated. Use
the TensorIndexType.delta attribute instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensorindextype-methods",
)
def get_kronecker_delta(self):
sym2 = TensorSymmetry(get_symmetric_group_sgs(2))
delta = TensorHead('KD', [self]*2, sym2)
return delta
@deprecated(
"""
The TensorIndexType.get_epsilon() method is deprecated. Use
the TensorIndexType.epsilon attribute instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensorindextype-methods",
)
def get_epsilon(self):
if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)):
return None
sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1))
epsilon = TensorHead('Eps', [self]*self._eps_dim, sym)
return epsilon
def _components_data_full_destroy(self):
"""
EXPERIMENTAL: do not rely on this API method.
This destroys components data associated to the ``TensorIndexType``, if
any, specifically:
* metric tensor data
* Kronecker tensor data
"""
if self in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self]
def delete_tensmul_data(key):
if key in _tensor_data_substitution_dict._substitutions_dict_tensmul:
del _tensor_data_substitution_dict._substitutions_dict_tensmul[key]
# delete metric data:
delete_tensmul_data((self.metric, True, True))
delete_tensmul_data((self.metric, True, False))
delete_tensmul_data((self.metric, False, True))
delete_tensmul_data((self.metric, False, False))
# delete delta tensor data:
delta = self.get_kronecker_delta()
if delta in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[delta]
class TensorIndex(Basic):
"""
Represents a tensor index
Parameters
==========
name : name of the index, or ``True`` if you want it to be automatically assigned
tensor_index_type : ``TensorIndexType`` of the index
is_up : flag for contravariant index (is_up=True by default)
Attributes
==========
``name``
``tensor_index_type``
``is_up``
Notes
=====
Tensor indices are contracted with the Einstein summation convention.
An index can be in contravariant or in covariant form; in the latter
case it is represented prepending a ``-`` to the index name. Adding
``-`` to a covariant (is_up=False) index makes it contravariant.
Dummy indices have a name with head given by
``tensor_inde_type.dummy_name`` with underscore and a number.
Similar to ``symbols`` multiple contravariant indices can be created
at once using ``tensor_indices(s, typ)``, where ``s`` is a string
of names.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> mu = TensorIndex('mu', Lorentz, is_up=False)
>>> nu, rho = tensor_indices('nu, rho', Lorentz)
>>> A = TensorHead('A', [Lorentz, Lorentz])
>>> A(mu, nu)
A(-mu, nu)
>>> A(-mu, -rho)
A(mu, -rho)
>>> A(mu, -mu)
A(-L_0, L_0)
"""
def __new__(cls, name, tensor_index_type, is_up=True):
if isinstance(name, str):
name_symbol = Symbol(name)
elif isinstance(name, Symbol):
name_symbol = name
elif name is True:
name = "_i{}".format(len(tensor_index_type._autogenerated))
name_symbol = Symbol(name)
tensor_index_type._autogenerated.append(name_symbol)
else:
raise ValueError("invalid name")
is_up = sympify(is_up)
return Basic.__new__(cls, name_symbol, tensor_index_type, is_up)
@property
def name(self):
return self.args[0].name
@property
def tensor_index_type(self):
return self.args[1]
@property
def is_up(self):
return self.args[2]
def _print(self):
s = self.name
if not self.is_up:
s = '-%s' % s
return s
def __lt__(self, other):
return ((self.tensor_index_type, self.name) <
(other.tensor_index_type, other.name))
def __neg__(self):
t1 = TensorIndex(self.name, self.tensor_index_type,
(not self.is_up))
return t1
def tensor_indices(s, typ):
"""
Returns list of tensor indices given their names and their types.
Parameters
==========
s : string of comma separated names of indices
typ : ``TensorIndexType`` of the indices
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
"""
if isinstance(s, str):
a = [x.name for x in symbols(s, seq=True)]
else:
raise ValueError('expecting a string')
tilist = [TensorIndex(i, typ) for i in a]
if len(tilist) == 1:
return tilist[0]
return tilist
class TensorSymmetry(Basic):
"""
Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric
index permutation). For the relevant terminology see ``tensor_can.py``
section of the combinatorics module.
Parameters
==========
bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor
Attributes
==========
``base`` : base of the BSGS
``generators`` : generators of the BSGS
``rank`` : rank of the tensor
Notes
=====
A tensor can have an arbitrary monoterm symmetry provided by its BSGS.
Multiterm symmetries, like the cyclic symmetry of the Riemann tensor
(i.e., Bianchi identity), are not covered. See combinatorics module for
information on how to generate BSGS for a general index permutation group.
Simple symmetries can be generated using built-in methods.
See Also
========
sympy.combinatorics.tensor_can.get_symmetric_group_sgs
Examples
========
Define a symmetric tensor of rank 2
>>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> sym = TensorSymmetry(get_symmetric_group_sgs(2))
>>> T = TensorHead('T', [Lorentz]*2, sym)
Note, that the same can also be done using built-in TensorSymmetry methods
>>> sym2 = TensorSymmetry.fully_symmetric(2)
>>> sym == sym2
True
"""
def __new__(cls, *args, **kw_args):
if len(args) == 1:
base, generators = args[0]
elif len(args) == 2:
base, generators = args
else:
raise TypeError("bsgs required, either two separate parameters or one tuple")
if not isinstance(base, Tuple):
base = Tuple(*base)
if not isinstance(generators, Tuple):
generators = Tuple(*generators)
return Basic.__new__(cls, base, generators, **kw_args)
@property
def base(self):
return self.args[0]
@property
def generators(self):
return self.args[1]
@property
def rank(self):
return self.generators[0].size - 2
@classmethod
def fully_symmetric(cls, rank):
"""
Returns a fully symmetric (antisymmetric if ``rank``<0)
TensorSymmetry object for ``abs(rank)`` indices.
"""
if rank > 0:
bsgs = get_symmetric_group_sgs(rank, False)
elif rank < 0:
bsgs = get_symmetric_group_sgs(-rank, True)
elif rank == 0:
bsgs = ([], [Permutation(1)])
return TensorSymmetry(bsgs)
@classmethod
def direct_product(cls, *args):
"""
Returns a TensorSymmetry object that is being a direct product of
fully (anti-)symmetric index permutation groups.
Notes
=====
Some examples for different values of ``(*args)``:
``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)``
``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)``
``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)``
``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting
``(1, 1, 1)`` tensor with 3 indices without any symmetry
"""
base, sgs = [], [Permutation(1)]
for arg in args:
if arg > 0:
bsgs2 = get_symmetric_group_sgs(arg, False)
elif arg < 0:
bsgs2 = get_symmetric_group_sgs(-arg, True)
else:
continue
base, sgs = bsgs_direct_product(base, sgs, *bsgs2)
return TensorSymmetry(base, sgs)
@classmethod
def riemann(cls):
"""
Returns a monotorem symmetry of the Riemann tensor
"""
return TensorSymmetry(riemann_bsgs)
@classmethod
def no_symmetry(cls, rank):
"""
TensorSymmetry object for ``rank`` indices with no symmetry
"""
return TensorSymmetry([], [Permutation(rank+1)])
@deprecated(
"""
The tensorsymmetry() function is deprecated. Use the TensorSymmetry
constructor instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensorsymmetry",
)
def tensorsymmetry(*args):
"""
Returns a ``TensorSymmetry`` object. This method is deprecated, use
``TensorSymmetry.direct_product()`` or ``.riemann()`` instead.
Explanation
===========
One can represent a tensor with any monoterm slot symmetry group
using a BSGS.
``args`` can be a BSGS
``args[0]`` base
``args[1]`` sgs
Usually tensors are in (direct products of) representations
of the symmetric group;
``args`` can be a list of lists representing the shapes of Young tableaux
Notes
=====
For instance:
``[[1]]`` vector
``[[1]*n]`` symmetric tensor of rank ``n``
``[[n]]`` antisymmetric tensor of rank ``n``
``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor
``[[1],[1]]`` vector*vector
``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector
Notice that with the shape ``[2, 2]`` we associate only the monoterm
symmetries of the Riemann tensor; this is an abuse of notation,
since the shape ``[2, 2]`` corresponds usually to the irreducible
representation characterized by the monoterm symmetries and by the
cyclic symmetry.
"""
from sympy.combinatorics import Permutation
def tableau2bsgs(a):
if len(a) == 1:
# antisymmetric vector
n = a[0]
bsgs = get_symmetric_group_sgs(n, 1)
else:
if all(x == 1 for x in a):
# symmetric vector
n = len(a)
bsgs = get_symmetric_group_sgs(n)
elif a == [2, 2]:
bsgs = riemann_bsgs
else:
raise NotImplementedError
return bsgs
if not args:
return TensorSymmetry(Tuple(), Tuple(Permutation(1)))
if len(args) == 2 and isinstance(args[1][0], Permutation):
return TensorSymmetry(args)
base, sgs = tableau2bsgs(args[0])
for a in args[1:]:
basex, sgsx = tableau2bsgs(a)
base, sgs = bsgs_direct_product(base, sgs, basex, sgsx)
return TensorSymmetry(Tuple(base, sgs))
@deprecated(
"TensorType is deprecated. Use tensor_heads() instead.",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensortype",
)
class TensorType(Basic):
"""
Class of tensor types. Deprecated, use tensor_heads() instead.
Parameters
==========
index_types : list of ``TensorIndexType`` of the tensor indices
symmetry : ``TensorSymmetry`` of the tensor
Attributes
==========
``index_types``
``symmetry``
``types`` : list of ``TensorIndexType`` without repetitions
"""
is_commutative = False
def __new__(cls, index_types, symmetry, **kw_args):
assert symmetry.rank == len(index_types)
obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args)
return obj
@property
def index_types(self):
return self.args[0]
@property
def symmetry(self):
return self.args[1]
@property
def types(self):
return sorted(set(self.index_types), key=lambda x: x.name)
def __str__(self):
return 'TensorType(%s)' % ([str(x) for x in self.index_types])
def __call__(self, s, comm=0):
"""
Return a TensorHead object or a list of TensorHead objects.
Parameters
==========
s : name or string of names.
comm : Commutation group.
see ``_TensorManager.set_comm``
"""
if isinstance(s, str):
names = [x.name for x in symbols(s, seq=True)]
else:
raise ValueError('expecting a string')
if len(names) == 1:
return TensorHead(names[0], self.index_types, self.symmetry, comm)
else:
return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names]
@deprecated(
"""
The tensorhead() function is deprecated. Use tensor_heads() instead.
""",
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensorhead",
)
def tensorhead(name, typ, sym=None, comm=0):
"""
Function generating tensorhead(s). This method is deprecated,
use TensorHead constructor or tensor_heads() instead.
Parameters
==========
name : name or sequence of names (as in ``symbols``)
typ : index types
sym : same as ``*args`` in ``tensorsymmetry``
comm : commutation group number
see ``_TensorManager.set_comm``
"""
if sym is None:
sym = [[1] for i in range(len(typ))]
with ignore_warnings(SymPyDeprecationWarning):
sym = tensorsymmetry(*sym)
return TensorHead(name, typ, sym, comm)
class TensorHead(Basic):
"""
Tensor head of the tensor.
Parameters
==========
name : name of the tensor
index_types : list of TensorIndexType
symmetry : TensorSymmetry of the tensor
comm : commutation group number
Attributes
==========
``name``
``index_types``
``rank`` : total number of indices
``symmetry``
``comm`` : commutation group
Notes
=====
Similar to ``symbols`` multiple TensorHeads can be created using
``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s``
is the string of names and ``sym`` is the monoterm tensor symmetry
(see ``tensorsymmetry``).
A ``TensorHead`` belongs to a commutation group, defined by a
symbol on number ``comm`` (see ``_TensorManager.set_comm``);
tensors in a commutation group have the same commutation properties;
by default ``comm`` is ``0``, the group of the commuting tensors.
Examples
========
Define a fully antisymmetric tensor of rank 2:
>>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> asym2 = TensorSymmetry.fully_symmetric(-2)
>>> A = TensorHead('A', [Lorentz, Lorentz], asym2)
Examples with ndarray values, the components data assigned to the
``TensorHead`` object are assumed to be in a fully-contravariant
representation. In case it is necessary to assign components data which
represents the values of a non-fully covariant tensor, see the other
examples.
>>> from sympy.tensor.tensor import tensor_indices
>>> from sympy import diag
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> i0, i1 = tensor_indices('i0:2', Lorentz)
Specify a replacement dictionary to keep track of the arrays to use for
replacements in the tensorial expression. The ``TensorIndexType`` is
associated to the metric used for contractions (in fully covariant form):
>>> repl = {Lorentz: diag(1, -1, -1, -1)}
Let's see some examples of working with components with the electromagnetic
tensor:
>>> from sympy import symbols
>>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
>>> c = symbols('c', positive=True)
Let's define `F`, an antisymmetric tensor:
>>> F = TensorHead('F', [Lorentz, Lorentz], asym2)
Let's update the dictionary to contain the matrix to use in the
replacements:
>>> repl.update({F(-i0, -i1): [
... [0, Ex/c, Ey/c, Ez/c],
... [-Ex/c, 0, -Bz, By],
... [-Ey/c, Bz, 0, -Bx],
... [-Ez/c, -By, Bx, 0]]})
Now it is possible to retrieve the contravariant form of the Electromagnetic
tensor:
>>> F(i0, i1).replace_with_arrays(repl, [i0, i1])
[[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]]
and the mixed contravariant-covariant form:
>>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1])
[[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]]
Energy-momentum of a particle may be represented as:
>>> from sympy import symbols
>>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1))
>>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True)
>>> repl.update({P(i0): [E, px, py, pz]})
The contravariant and covariant components are, respectively:
>>> P(i0).replace_with_arrays(repl, [i0])
[E, p_x, p_y, p_z]
>>> P(-i0).replace_with_arrays(repl, [-i0])
[E, -p_x, -p_y, -p_z]
The contraction of a 1-index tensor by itself:
>>> expr = P(i0)*P(-i0)
>>> expr.replace_with_arrays(repl, [])
E**2 - p_x**2 - p_y**2 - p_z**2
"""
is_commutative = False
def __new__(cls, name, index_types, symmetry=None, comm=0):
if isinstance(name, str):
name_symbol = Symbol(name)
elif isinstance(name, Symbol):
name_symbol = name
else:
raise ValueError("invalid name")
if symmetry is None:
symmetry = TensorSymmetry.no_symmetry(len(index_types))
else:
assert symmetry.rank == len(index_types)
obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry, sympify(comm))
return obj
@property
def name(self):
return self.args[0].name
@property
def index_types(self):
return list(self.args[1])
@property
def symmetry(self):
return self.args[2]
@property
def comm(self):
return TensorManager.comm_symbols2i(self.args[3])
@property
def rank(self):
return len(self.index_types)
def __lt__(self, other):
return (self.name, self.index_types) < (other.name, other.index_types)
def commutes_with(self, other):
"""
Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute.
Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute.
"""
r = TensorManager.get_comm(self.comm, other.comm)
return r
def _print(self):
return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types]))
def __call__(self, *indices, **kw_args):
"""
Returns a tensor with indices.
Explanation
===========
There is a special behavior in case of indices denoted by ``True``,
they are considered auto-matrix indices, their slots are automatically
filled, and confer to the tensor the behavior of a matrix or vector
upon multiplication with another tensor containing auto-matrix indices
of the same ``TensorIndexType``. This means indices get summed over the
same way as in matrix multiplication. For matrix behavior, define two
auto-matrix indices, for vector behavior define just one.
Indices can also be strings, in which case the attribute
``index_types`` is used to convert them to proper ``TensorIndex``.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> a, b = tensor_indices('a,b', Lorentz)
>>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
>>> t = A(a, -b)
>>> t
A(a, -b)
"""
updated_indices = []
for idx, typ in zip(indices, self.index_types):
if isinstance(idx, str):
idx = idx.strip().replace(" ", "")
if idx.startswith('-'):
updated_indices.append(TensorIndex(idx[1:], typ,
is_up=False))
else:
updated_indices.append(TensorIndex(idx, typ))
else:
updated_indices.append(idx)
updated_indices += indices[len(updated_indices):]
tensor = Tensor(self, updated_indices, **kw_args)
return tensor.doit()
# Everything below this line is deprecated
def __pow__(self, other):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if self.data is None:
raise ValueError("No power on abstract tensors.")
from .array import tensorproduct, tensorcontraction
metrics = [_.data for _ in self.index_types]
marray = self.data
marraydim = marray.rank()
for metric in metrics:
marray = tensorproduct(marray, metric, marray)
marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2))
return marray ** (other * S.Half)
@property
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return _tensor_data_substitution_dict[self]
@data.setter
def data(self, data):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
_tensor_data_substitution_dict[self] = data
@data.deleter
def data(self):
deprecate_data()
if self in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self]
def __iter__(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return self.data.__iter__()
def _components_data_full_destroy(self):
"""
EXPERIMENTAL: do not rely on this API method.
Destroy components data associated to the ``TensorHead`` object, this
checks for attached components data, and destroys components data too.
"""
# do not garbage collect Kronecker tensor (it should be done by
# ``TensorIndexType`` garbage collection)
deprecate_data()
if self.name == "KD":
return
# the data attached to a tensor must be deleted only by the TensorHead
# destructor. If the TensorHead is deleted, it means that there are no
# more instances of that tensor anywhere.
if self in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self]
def tensor_heads(s, index_types, symmetry=None, comm=0):
"""
Returns a sequence of TensorHeads from a string `s`
"""
if isinstance(s, str):
names = [x.name for x in symbols(s, seq=True)]
else:
raise ValueError('expecting a string')
thlist = [TensorHead(name, index_types, symmetry, comm) for name in names]
if len(thlist) == 1:
return thlist[0]
return thlist
class TensExpr(Expr, ABC):
"""
Abstract base class for tensor expressions
Notes
=====
A tensor expression is an expression formed by tensors;
currently the sums of tensors are distributed.
A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``.
``TensMul`` objects are formed by products of component tensors,
and include a coefficient, which is a SymPy expression.
In the internal representation contracted indices are represented
by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position
of the component tensor with contravariant index, ``ipos1`` is the
slot which the index occupies in that component tensor.
Contracted indices are therefore nameless in the internal representation.
"""
_op_priority = 12.0
is_commutative = False
def __neg__(self):
return self*S.NegativeOne
def __abs__(self):
raise NotImplementedError
def __add__(self, other):
return TensAdd(self, other).doit()
def __radd__(self, other):
return TensAdd(other, self).doit()
def __sub__(self, other):
return TensAdd(self, -other).doit()
def __rsub__(self, other):
return TensAdd(other, -self).doit()
def __mul__(self, other):
"""
Multiply two tensors using Einstein summation convention.
Explanation
===========
If the two tensors have an index in common, one contravariant
and the other covariant, in their product the indices are summed
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
>>> g = Lorentz.metric
>>> p, q = tensor_heads('p,q', [Lorentz])
>>> t1 = p(m0)
>>> t2 = q(-m0)
>>> t1*t2
p(L_0)*q(-L_0)
"""
return TensMul(self, other).doit()
def __rmul__(self, other):
return TensMul(other, self).doit()
def __truediv__(self, other):
other = _sympify(other)
if isinstance(other, TensExpr):
raise ValueError('cannot divide by a tensor')
return TensMul(self, S.One/other).doit()
def __rtruediv__(self, other):
raise ValueError('cannot divide by a tensor')
def __pow__(self, other):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if self.data is None:
raise ValueError("No power without ndarray data.")
from .array import tensorproduct, tensorcontraction
free = self.free
marray = self.data
mdim = marray.rank()
for metric in free:
marray = tensorcontraction(
tensorproduct(
marray,
metric[0].tensor_index_type.data,
marray),
(0, mdim), (mdim+1, mdim+2)
)
return marray ** (other * S.Half)
def __rpow__(self, other):
raise NotImplementedError
@property
@abstractmethod
def nocoeff(self):
raise NotImplementedError("abstract method")
@property
@abstractmethod
def coeff(self):
raise NotImplementedError("abstract method")
@abstractmethod
def get_indices(self):
raise NotImplementedError("abstract method")
@abstractmethod
def get_free_indices(self) -> list[TensorIndex]:
raise NotImplementedError("abstract method")
@abstractmethod
def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
raise NotImplementedError("abstract method")
def fun_eval(self, *index_tuples):
deprecate_fun_eval()
return self.substitute_indices(*index_tuples)
def get_matrix(self):
"""
DEPRECATED: do not use.
Returns ndarray components data as a matrix, if components data are
available and ndarray dimension does not exceed 2.
"""
from sympy.matrices.dense import Matrix
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if 0 < self.rank <= 2:
rows = self.data.shape[0]
columns = self.data.shape[1] if self.rank == 2 else 1
if self.rank == 2:
mat_list = [] * rows
for i in range(rows):
mat_list.append([])
for j in range(columns):
mat_list[i].append(self[i, j])
else:
mat_list = [None] * rows
for i in range(rows):
mat_list[i] = self[i]
return Matrix(mat_list)
else:
raise NotImplementedError(
"missing multidimensional reduction to matrix.")
@staticmethod
def _get_indices_permutation(indices1, indices2):
return [indices1.index(i) for i in indices2]
def expand(self, **hints):
return _expand(self, **hints).doit()
def _expand(self, **kwargs):
return self
def _get_free_indices_set(self):
indset = set()
for arg in self.args:
if isinstance(arg, TensExpr):
indset.update(arg._get_free_indices_set())
return indset
def _get_dummy_indices_set(self):
indset = set()
for arg in self.args:
if isinstance(arg, TensExpr):
indset.update(arg._get_dummy_indices_set())
return indset
def _get_indices_set(self):
indset = set()
for arg in self.args:
if isinstance(arg, TensExpr):
indset.update(arg._get_indices_set())
return indset
@property
def _iterate_dummy_indices(self):
dummy_set = self._get_dummy_indices_set()
def recursor(expr, pos):
if isinstance(expr, TensorIndex):
if expr in dummy_set:
yield (expr, pos)
elif isinstance(expr, (Tuple, TensExpr)):
for p, arg in enumerate(expr.args):
yield from recursor(arg, pos+(p,))
return recursor(self, ())
@property
def _iterate_free_indices(self):
free_set = self._get_free_indices_set()
def recursor(expr, pos):
if isinstance(expr, TensorIndex):
if expr in free_set:
yield (expr, pos)
elif isinstance(expr, (Tuple, TensExpr)):
for p, arg in enumerate(expr.args):
yield from recursor(arg, pos+(p,))
return recursor(self, ())
@property
def _iterate_indices(self):
def recursor(expr, pos):
if isinstance(expr, TensorIndex):
yield (expr, pos)
elif isinstance(expr, (Tuple, TensExpr)):
for p, arg in enumerate(expr.args):
yield from recursor(arg, pos+(p,))
return recursor(self, ())
@staticmethod
def _contract_and_permute_with_metric(metric, array, pos, dim):
# TODO: add possibility of metric after (spinors)
from .array import tensorcontraction, tensorproduct, permutedims
array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))
permu = list(range(dim))
permu[0], permu[pos] = permu[pos], permu[0]
return permutedims(array, permu)
@staticmethod
def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):
from .array import permutedims
index_types1 = [i.tensor_index_type for i in free_ind1]
# Check if variance of indices needs to be fixed:
pos2up = []
pos2down = []
free2remaining = free_ind2[:]
for pos1, index1 in enumerate(free_ind1):
if index1 in free2remaining:
pos2 = free2remaining.index(index1)
free2remaining[pos2] = None
continue
if -index1 in free2remaining:
pos2 = free2remaining.index(-index1)
free2remaining[pos2] = None
free_ind2[pos2] = index1
if index1.is_up:
pos2up.append(pos2)
else:
pos2down.append(pos2)
else:
index2 = free2remaining[pos1]
if index2 is None:
raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
free2remaining[pos1] = None
free_ind2[pos1] = index1
if index1.is_up ^ index2.is_up:
if index1.is_up:
pos2up.append(pos1)
else:
pos2down.append(pos1)
if len(set(free_ind1) & set(free_ind2)) < len(free_ind1):
raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
# Raise indices:
for pos in pos2up:
index_type_pos = index_types1[pos]
if index_type_pos not in replacement_dict:
raise ValueError("No metric provided to lower index")
metric = replacement_dict[index_type_pos]
metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric)
array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1))
# Lower indices:
for pos in pos2down:
index_type_pos = index_types1[pos]
if index_type_pos not in replacement_dict:
raise ValueError("No metric provided to lower index")
metric = replacement_dict[index_type_pos]
array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1))
if free_ind1:
permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1)
array = permutedims(array, permutation)
if hasattr(array, "rank") and array.rank() == 0:
array = array[()]
return free_ind2, array
def replace_with_arrays(self, replacement_dict, indices=None):
"""
Replace the tensorial expressions with arrays. The final array will
correspond to the N-dimensional array with indices arranged according
to ``indices``.
Parameters
==========
replacement_dict
dictionary containing the replacement rules for tensors.
indices
the index order with respect to which the array is read. The
original index order will be used if no value is passed.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
>>> from sympy.tensor.tensor import TensorHead
>>> from sympy import symbols, diag
>>> L = TensorIndexType("L")
>>> i, j = tensor_indices("i j", L)
>>> A = TensorHead("A", [L])
>>> A(i).replace_with_arrays({A(i): [1, 2]}, [i])
[1, 2]
Since 'indices' is optional, we can also call replace_with_arrays by
this way if no specific index order is needed:
>>> A(i).replace_with_arrays({A(i): [1, 2]})
[1, 2]
>>> expr = A(i)*A(j)
>>> expr.replace_with_arrays({A(i): [1, 2]})
[[1, 2], [2, 4]]
For contractions, specify the metric of the ``TensorIndexType``, which
in this case is ``L``, in its covariant form:
>>> expr = A(i)*A(-i)
>>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)})
-3
Symmetrization of an array:
>>> H = TensorHead("H", [L, L])
>>> a, b, c, d = symbols("a b c d")
>>> expr = H(i, j)/2 + H(j, i)/2
>>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]})
[[a, b/2 + c/2], [b/2 + c/2, d]]
Anti-symmetrization of an array:
>>> expr = H(i, j)/2 - H(j, i)/2
>>> repl = {H(i, j): [[a, b], [c, d]]}
>>> expr.replace_with_arrays(repl)
[[0, b/2 - c/2], [-b/2 + c/2, 0]]
The same expression can be read as the transpose by inverting ``i`` and
``j``:
>>> expr.replace_with_arrays(repl, [j, i])
[[0, -b/2 + c/2], [b/2 - c/2, 0]]
"""
from .array import Array
indices = indices or []
remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()}
for i, index in enumerate(indices):
if isinstance(index, (Symbol, Mul)):
if index in remap:
indices[i] = remap[index]
else:
indices[i] = -remap[-index]
replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()}
# Check dimensions of replaced arrays:
for tensor, array in replacement_dict.items():
if isinstance(tensor, TensorIndexType):
expected_shape = [tensor.dim for i in range(2)]
else:
expected_shape = [index_type.dim for index_type in tensor.index_types]
if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if
dim1.is_number else True for dim1, dim2 in zip(expected_shape,
array.shape))):
raise ValueError("shapes for tensor %s expected to be %s, "\
"replacement array shape is %s" % (tensor, expected_shape,
array.shape))
ret_indices, array = self._extract_data(replacement_dict)
last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict)
return array
def _check_add_Sum(self, expr, index_symbols):
from sympy.concrete.summations import Sum
indices = self.get_indices()
dum = self.dum
sum_indices = [ (index_symbols[i], 0,
indices[i].tensor_index_type.dim-1) for i, j in dum]
if sum_indices:
expr = Sum(expr, *sum_indices)
return expr
def _expand_partial_derivative(self):
# simply delegate the _expand_partial_derivative() to
# its arguments to expand a possibly found PartialDerivative
return self.func(*[
a._expand_partial_derivative()
if isinstance(a, TensExpr) else a
for a in self.args])
class TensAdd(TensExpr, AssocOp):
"""
Sum of tensors.
Parameters
==========
free_args : list of the free indices
Attributes
==========
``args`` : tuple of addends
``rank`` : rank of the tensor
``free_args`` : list of the free indices in sorted order
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> a, b = tensor_indices('a,b', Lorentz)
>>> p, q = tensor_heads('p,q', [Lorentz])
>>> t = p(a) + q(a); t
p(a) + q(a)
Examples with components data added to the tensor expression:
>>> from sympy import symbols, diag
>>> x, y, z, t = symbols("x y z t")
>>> repl = {}
>>> repl[Lorentz] = diag(1, -1, -1, -1)
>>> repl[p(a)] = [1, 2, 3, 4]
>>> repl[q(a)] = [x, y, z, t]
The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58
>>> expr = p(a) + q(a)
>>> expr.replace_with_arrays(repl, [a])
[x + 1, y + 2, z + 3, t + 4]
"""
def __new__(cls, *args, **kw_args):
args = [_sympify(x) for x in args if x]
args = TensAdd._tensAdd_flatten(args)
args.sort(key=default_sort_key)
if not args:
return S.Zero
if len(args) == 1:
return args[0]
return Basic.__new__(cls, *args, **kw_args)
@property
def coeff(self):
return S.One
@property
def nocoeff(self):
return self
def get_free_indices(self) -> list[TensorIndex]:
return self.free_indices
def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]
return self.func(*newargs)
@memoize_property
def rank(self):
if isinstance(self.args[0], TensExpr):
return self.args[0].rank
else:
return 0
@memoize_property
def free_args(self):
if isinstance(self.args[0], TensExpr):
return self.args[0].free_args
else:
return []
@memoize_property
def free_indices(self):
if isinstance(self.args[0], TensExpr):
return self.args[0].get_free_indices()
else:
return set()
def doit(self, **hints):
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
else:
args = self.args
# if any of the args are zero (after doit), drop them. Otherwise, _tensAdd_check will complain about non-matching indices, even though the TensAdd is correctly formed.
args = [arg for arg in args if arg != S.Zero]
if len(args) == 0:
return S.Zero
elif len(args) == 1:
return args[0]
# now check that all addends have the same indices:
TensAdd._tensAdd_check(args)
# Collect terms appearing more than once, differing by their coefficients:
args = TensAdd._tensAdd_collect_terms(args)
# collect canonicalized terms
def sort_key(t):
if not isinstance(t, TensExpr):
return [], [], []
if hasattr(t, "_index_structure") and hasattr(t, "components"):
x = get_index_structure(t)
return t.components, x.free, x.dum
return [], [], []
args.sort(key=sort_key)
if not args:
return S.Zero
# it there is only a component tensor return it
if len(args) == 1:
return args[0]
obj = self.func(*args)
return obj
@staticmethod
def _tensAdd_flatten(args):
# flatten TensAdd, coerce terms which are not tensors to tensors
a = []
for x in args:
if isinstance(x, (Add, TensAdd)):
a.extend(list(x.args))
else:
a.append(x)
args = [x for x in a if x.coeff]
return args
@staticmethod
def _tensAdd_check(args):
# check that all addends have the same free indices
def get_indices_set(x: Expr) -> set[TensorIndex]:
if isinstance(x, TensExpr):
return set(x.get_free_indices())
return set()
indices0 = get_indices_set(args[0])
list_indices = [get_indices_set(arg) for arg in args[1:]]
if not all(x == indices0 for x in list_indices):
raise ValueError('all tensors must have the same indices')
@staticmethod
def _tensAdd_collect_terms(args):
# collect TensMul terms differing at most by their coefficient
terms_dict = defaultdict(list)
scalars = S.Zero
if isinstance(args[0], TensExpr):
free_indices = set(args[0].get_free_indices())
else:
free_indices = set()
for arg in args:
if not isinstance(arg, TensExpr):
if free_indices != set():
raise ValueError("wrong valence")
scalars += arg
continue
if free_indices != set(arg.get_free_indices()):
raise ValueError("wrong valence")
# TODO: what is the part which is not a coeff?
# needs an implementation similar to .as_coeff_Mul()
terms_dict[arg.nocoeff].append(arg.coeff)
new_args = [TensMul(Add(*coeff), t).doit() for t, coeff in terms_dict.items() if Add(*coeff) != 0]
if isinstance(scalars, Add):
new_args = list(scalars.args) + new_args
elif scalars != 0:
new_args = [scalars] + new_args
return new_args
def get_indices(self):
indices = []
for arg in self.args:
indices.extend([i for i in get_indices(arg) if i not in indices])
return indices
def _expand(self, **hints):
return TensAdd(*[_expand(i, **hints) for i in self.args])
def __call__(self, *indices):
deprecate_call()
free_args = self.free_args
indices = list(indices)
if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
raise ValueError('incompatible types')
if indices == free_args:
return self
index_tuples = list(zip(free_args, indices))
a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args]
res = TensAdd(*a).doit()
return res
def canon_bp(self):
"""
Canonicalize using the Butler-Portugal algorithm for canonicalization
under monoterm symmetries.
"""
expr = self.expand()
args = [canon_bp(x) for x in expr.args]
res = TensAdd(*args).doit()
return res
def equals(self, other):
other = _sympify(other)
if isinstance(other, TensMul) and other.coeff == 0:
return all(x.coeff == 0 for x in self.args)
if isinstance(other, TensExpr):
if self.rank != other.rank:
return False
if isinstance(other, TensAdd):
if set(self.args) != set(other.args):
return False
else:
return True
t = self - other
if not isinstance(t, TensExpr):
return t == 0
else:
if isinstance(t, TensMul):
return t.coeff == 0
else:
return all(x.coeff == 0 for x in t.args)
def __getitem__(self, item):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return self.data[item]
def contract_delta(self, delta):
args = [x.contract_delta(delta) for x in self.args]
t = TensAdd(*args).doit()
return canon_bp(t)
def contract_metric(self, g):
"""
Raise or lower indices with the metric ``g``.
Parameters
==========
g : metric
contract_all : if True, eliminate all ``g`` which are contracted
Notes
=====
see the ``TensorIndexType`` docstring for the contraction conventions
"""
args = [contract_metric(x, g) for x in self.args]
t = TensAdd(*args).doit()
return canon_bp(t)
def substitute_indices(self, *index_tuples):
new_args = []
for arg in self.args:
if isinstance(arg, TensExpr):
arg = arg.substitute_indices(*index_tuples)
new_args.append(arg)
return TensAdd(*new_args).doit()
def _print(self):
a = []
args = self.args
for x in args:
a.append(str(x))
s = ' + '.join(a)
s = s.replace('+ -', '- ')
return s
def _extract_data(self, replacement_dict):
from sympy.tensor.array import Array, permutedims
args_indices, arrays = zip(*[
arg._extract_data(replacement_dict) if
isinstance(arg, TensExpr) else ([], arg) for arg in self.args
])
arrays = [Array(i) for i in arrays]
ref_indices = args_indices[0]
for i in range(1, len(args_indices)):
indices = args_indices[i]
array = arrays[i]
permutation = TensMul._get_indices_permutation(indices, ref_indices)
arrays[i] = permutedims(array, permutation)
return ref_indices, sum(arrays, Array.zeros(*array.shape))
@property
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return _tensor_data_substitution_dict[self.expand()]
@data.setter
def data(self, data):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
_tensor_data_substitution_dict[self] = data
@data.deleter
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if self in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self]
def __iter__(self):
deprecate_data()
if not self.data:
raise ValueError("No iteration on abstract tensors")
return self.data.flatten().__iter__()
def _eval_rewrite_as_Indexed(self, *args, **kwargs):
return Add.fromiter(args)
def _eval_partial_derivative(self, s):
# Evaluation like Add
list_addends = []
for a in self.args:
if isinstance(a, TensExpr):
list_addends.append(a._eval_partial_derivative(s))
# do not call diff if s is no symbol
elif s._diff_wrt:
list_addends.append(a._eval_derivative(s))
return self.func(*list_addends)
class Tensor(TensExpr):
"""
Base tensor class, i.e. this represents a tensor, the single unit to be
put into an expression.
Explanation
===========
This object is usually created from a ``TensorHead``, by attaching indices
to it. Indices preceded by a minus sign are considered contravariant,
otherwise covariant.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
>>> Lorentz = TensorIndexType("Lorentz", dummy_name="L")
>>> mu, nu = tensor_indices('mu nu', Lorentz)
>>> A = TensorHead("A", [Lorentz, Lorentz])
>>> A(mu, -nu)
A(mu, -nu)
>>> A(mu, -mu)
A(L_0, -L_0)
It is also possible to use symbols instead of inidices (appropriate indices
are then generated automatically).
>>> from sympy import Symbol
>>> x = Symbol('x')
>>> A(x, mu)
A(x, mu)
>>> A(x, -x)
A(L_0, -L_0)
"""
is_commutative = False
_index_structure = None # type: _IndexStructure
args: tuple[TensorHead, Tuple]
def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args):
indices = cls._parse_indices(tensor_head, indices)
obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args)
obj._index_structure = _IndexStructure.from_indices(*indices)
obj._free = obj._index_structure.free[:]
obj._dum = obj._index_structure.dum[:]
obj._ext_rank = obj._index_structure._ext_rank
obj._coeff = S.One
obj._nocoeff = obj
obj._component = tensor_head
obj._components = [tensor_head]
if tensor_head.rank != len(indices):
raise ValueError("wrong number of indices")
obj.is_canon_bp = is_canon_bp
obj._index_map = Tensor._build_index_map(indices, obj._index_structure)
return obj
@property
def free(self):
return self._free
@property
def dum(self):
return self._dum
@property
def ext_rank(self):
return self._ext_rank
@property
def coeff(self):
return self._coeff
@property
def nocoeff(self):
return self._nocoeff
@property
def component(self):
return self._component
@property
def components(self):
return self._components
@property
def head(self):
return self.args[0]
@property
def indices(self):
return self.args[1]
@property
def free_indices(self):
return set(self._index_structure.get_free_indices())
@property
def index_types(self):
return self.head.index_types
@property
def rank(self):
return len(self.free_indices)
@staticmethod
def _build_index_map(indices, index_structure):
index_map = {}
for idx in indices:
index_map[idx] = (indices.index(idx),)
return index_map
def doit(self, **hints):
args, indices, free, dum = TensMul._tensMul_contract_indices([self])
return args[0]
@staticmethod
def _parse_indices(tensor_head, indices):
if not isinstance(indices, (tuple, list, Tuple)):
raise TypeError("indices should be an array, got %s" % type(indices))
indices = list(indices)
for i, index in enumerate(indices):
if isinstance(index, Symbol):
indices[i] = TensorIndex(index, tensor_head.index_types[i], True)
elif isinstance(index, Mul):
c, e = index.as_coeff_Mul()
if c == -1 and isinstance(e, Symbol):
indices[i] = TensorIndex(e, tensor_head.index_types[i], False)
else:
raise ValueError("index not understood: %s" % index)
elif not isinstance(index, TensorIndex):
raise TypeError("wrong type for index: %s is %s" % (index, type(index)))
return indices
def _set_new_index_structure(self, im, is_canon_bp=False):
indices = im.get_indices()
return self._set_indices(*indices, is_canon_bp=is_canon_bp)
def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
if len(indices) != self.ext_rank:
raise ValueError("indices length mismatch")
return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit()
def _get_free_indices_set(self):
return {i[0] for i in self._index_structure.free}
def _get_dummy_indices_set(self):
dummy_pos = set(itertools.chain(*self._index_structure.dum))
return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos}
def _get_indices_set(self):
return set(self.args[1].args)
@property
def free_in_args(self):
return [(ind, pos, 0) for ind, pos in self.free]
@property
def dum_in_args(self):
return [(p1, p2, 0, 0) for p1, p2 in self.dum]
@property
def free_args(self):
return sorted([x[0] for x in self.free])
def commutes_with(self, other):
"""
:param other:
:return:
0 commute
1 anticommute
None neither commute nor anticommute
"""
if not isinstance(other, TensExpr):
return 0
elif isinstance(other, Tensor):
return self.component.commutes_with(other.component)
return NotImplementedError
def perm2tensor(self, g, is_canon_bp=False):
"""
Returns the tensor corresponding to the permutation ``g``.
For further details, see the method in ``TIDS`` with the same name.
"""
return perm2tensor(self, g, is_canon_bp)
def canon_bp(self):
if self.is_canon_bp:
return self
expr = self.expand()
g, dummies, msym = expr._index_structure.indices_canon_args()
v = components_canon_args([expr.component])
can = canonicalize(g, dummies, msym, *v)
if can == 0:
return S.Zero
tensor = self.perm2tensor(can, True)
return tensor
def split(self):
return [self]
def _expand(self, **kwargs):
return self
def sorted_components(self):
return self
def get_indices(self) -> list[TensorIndex]:
"""
Get a list of indices, corresponding to those of the tensor.
"""
return list(self.args[1])
def get_free_indices(self) -> list[TensorIndex]:
"""
Get a list of free indices, corresponding to those of the tensor.
"""
return self._index_structure.get_free_indices()
def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
# TODO: this could be optimized by only swapping the indices
# instead of visiting the whole expression tree:
return self.xreplace(repl)
def as_base_exp(self):
return self, S.One
def substitute_indices(self, *index_tuples):
"""
Return a tensor with free indices substituted according to ``index_tuples``.
``index_types`` list of tuples ``(old_index, new_index)``.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
>>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
>>> t = A(i, k)*B(-k, -j); t
A(i, L_0)*B(-L_0, -j)
>>> t.substitute_indices((i, k),(-j, l))
A(k, L_0)*B(-L_0, l)
"""
indices = []
for index in self.indices:
for ind_old, ind_new in index_tuples:
if (index.name == ind_old.name and index.tensor_index_type ==
ind_old.tensor_index_type):
if index.is_up == ind_old.is_up:
indices.append(ind_new)
else:
indices.append(-ind_new)
break
else:
indices.append(index)
return self.head(*indices)
def _get_symmetrized_forms(self):
"""
Return a list giving all possible permutations of self that are allowed by its symmetries.
"""
comp = self.component
gens = comp.symmetry.generators
rank = comp.rank
old_perms = None
new_perms = {self}
while new_perms != old_perms:
old_perms = new_perms.copy()
for tens in old_perms:
for gen in gens:
inds = tens.get_indices()
per = [gen.apply(i) for i in range(0,rank)]
sign = (-1)**(gen.apply(rank) - rank)
ind_map = dict(zip(inds, [inds[i] for i in per]))
new_perms.add( sign * tens._replace_indices(ind_map) )
return new_perms
def matches(self, expr, repl_dict=None, old=False):
expr = sympify(expr)
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
#simple checks
if self == expr:
return repl_dict
if not isinstance(expr, Tensor):
return None
if self.head != expr.head:
return None
#Now consider all index symmetries of expr, and see if any of them allow a match.
for new_expr in expr._get_symmetrized_forms():
m = self._matches(new_expr, repl_dict, old=old)
if m is not None:
repl_dict.update(m)
return repl_dict
return None
def _matches(self, expr, repl_dict=None, old=False):
"""
This does not account for index symmetries of expr
"""
expr = sympify(expr)
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
#simple checks
if self == expr:
return repl_dict
if not isinstance(expr, Tensor):
return None
if self.head != expr.head:
return None
s_indices = self.get_indices()
e_indices = expr.get_indices()
if len(s_indices) != len(e_indices):
return None
for i in range(len(s_indices)):
s_ind = s_indices[i]
m = s_ind.matches(e_indices[i])
if m is None:
return None
elif -s_ind in repl_dict.keys() and -repl_dict[-s_ind] != m[s_ind]:
return None
else:
repl_dict.update(m)
return repl_dict
def __call__(self, *indices):
deprecate_call()
free_args = self.free_args
indices = list(indices)
if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
raise ValueError('incompatible types')
if indices == free_args:
return self
t = self.substitute_indices(*list(zip(free_args, indices)))
# object is rebuilt in order to make sure that all contracted indices
# get recognized as dummies, but only if there are contracted indices.
if len({i if i.is_up else -i for i in indices}) != len(indices):
return t.func(*t.args)
return t
# TODO: put this into TensExpr?
def __iter__(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return self.data.__iter__()
# TODO: put this into TensExpr?
def __getitem__(self, item):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return self.data[item]
def _extract_data(self, replacement_dict):
from .array import Array
for k, v in replacement_dict.items():
if isinstance(k, Tensor) and k.args[0] == self.args[0]:
other = k
array = v
break
else:
raise ValueError("%s not found in %s" % (self, replacement_dict))
# TODO: inefficient, this should be done at root level only:
replacement_dict = {k: Array(v) for k, v in replacement_dict.items()}
array = Array(array)
dum1 = self.dum
dum2 = other.dum
if len(dum2) > 0:
for pair in dum2:
# allow `dum2` if the contained values are also in `dum1`.
if pair not in dum1:
raise NotImplementedError("%s with contractions is not implemented" % other)
# Remove elements in `dum2` from `dum1`:
dum1 = [pair for pair in dum1 if pair not in dum2]
if len(dum1) > 0:
indices1 = self.get_indices()
indices2 = other.get_indices()
repl = {}
for p1, p2 in dum1:
repl[indices2[p2]] = -indices2[p1]
for pos in (p1, p2):
if indices1[pos].is_up ^ indices2[pos].is_up:
metric = replacement_dict[indices1[pos].tensor_index_type]
if indices1[pos].is_up:
metric = _TensorDataLazyEvaluator.inverse_matrix(metric)
array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2))
other = other.xreplace(repl).doit()
array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2))
free_ind1 = self.get_free_indices()
free_ind2 = other.get_free_indices()
return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict)
@property
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return _tensor_data_substitution_dict[self]
@data.setter
def data(self, data):
deprecate_data()
# TODO: check data compatibility with properties of tensor.
with ignore_warnings(SymPyDeprecationWarning):
_tensor_data_substitution_dict[self] = data
@data.deleter
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if self in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self]
if self.metric in _tensor_data_substitution_dict:
del _tensor_data_substitution_dict[self.metric]
def _print(self):
indices = [str(ind) for ind in self.indices]
component = self.component
if component.rank > 0:
return ('%s(%s)' % (component.name, ', '.join(indices)))
else:
return ('%s' % component.name)
def equals(self, other):
if other == 0:
return self.coeff == 0
other = _sympify(other)
if not isinstance(other, TensExpr):
assert not self.components
return S.One == other
def _get_compar_comp(self):
t = self.canon_bp()
r = (t.coeff, tuple(t.components), \
tuple(sorted(t.free)), tuple(sorted(t.dum)))
return r
return _get_compar_comp(self) == _get_compar_comp(other)
def contract_metric(self, g):
# if metric is not the same, ignore this step:
if self.component != g:
return self
# in case there are free components, do not perform anything:
if len(self.free) != 0:
return self
#antisym = g.index_types[0].metric_antisym
if g.symmetry == TensorSymmetry.fully_symmetric(-2):
antisym = 1
elif g.symmetry == TensorSymmetry.fully_symmetric(2):
antisym = 0
elif g.symmetry == TensorSymmetry.no_symmetry(2):
antisym = None
else:
raise NotImplementedError
sign = S.One
typ = g.index_types[0]
if not antisym:
# g(i, -i)
sign = sign*typ.dim
else:
# g(i, -i)
sign = sign*typ.dim
dp0, dp1 = self.dum[0]
if dp0 < dp1:
# g(i, -i) = -D with antisymmetric metric
sign = -sign
return sign
def contract_delta(self, metric):
return self.contract_metric(metric)
def _eval_rewrite_as_Indexed(self, tens, indices, **kwargs):
from sympy.tensor.indexed import Indexed
# TODO: replace .args[0] with .name:
index_symbols = [i.args[0] for i in self.get_indices()]
expr = Indexed(tens.args[0], *index_symbols)
return self._check_add_Sum(expr, index_symbols)
def _eval_partial_derivative(self, s): # type: (Tensor) -> Expr
if not isinstance(s, Tensor):
return S.Zero
else:
# @a_i/@a_k = delta_i^k
# @a_i/@a^k = g_ij delta^j_k
# @a^i/@a^k = delta^i_k
# @a^i/@a_k = g^ij delta_j^k
# TODO: if there is no metric present, the derivative should be zero?
if self.head != s.head:
return S.Zero
# if heads are the same, provide delta and/or metric products
# for every free index pair in the appropriate tensor
# assumed that the free indices are in proper order
# A contravariante index in the derivative becomes covariant
# after performing the derivative and vice versa
kronecker_delta_list = [1]
# not guarantee a correct index order
for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())):
if iself.tensor_index_type != iother.tensor_index_type:
raise ValueError("index types not compatible")
else:
tensor_index_type = iself.tensor_index_type
tensor_metric = tensor_index_type.metric
dummy = TensorIndex("d_" + str(count), tensor_index_type,
is_up=iself.is_up)
if iself.is_up == iother.is_up:
kroneckerdelta = tensor_index_type.delta(iself, -iother)
else:
kroneckerdelta = (
TensMul(tensor_metric(iself, dummy),
tensor_index_type.delta(-dummy, -iother))
)
kronecker_delta_list.append(kroneckerdelta)
return TensMul.fromiter(kronecker_delta_list).doit()
# doit necessary to rename dummy indices accordingly
class TensMul(TensExpr, AssocOp):
"""
Product of tensors.
Parameters
==========
coeff : SymPy coefficient of the tensor
args
Attributes
==========
``components`` : list of ``TensorHead`` of the component tensors
``types`` : list of nonrepeated ``TensorIndexType``
``free`` : list of ``(ind, ipos, icomp)``, see Notes
``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes
``ext_rank`` : rank of the tensor counting the dummy indices
``rank`` : rank of the tensor
``coeff`` : SymPy coefficient of the tensor
``free_args`` : list of the free indices in sorted order
``is_canon_bp`` : ``True`` if the tensor in in canonical form
Notes
=====
``args[0]`` list of ``TensorHead`` of the component tensors.
``args[1]`` list of ``(ind, ipos, icomp)``
where ``ind`` is a free index, ``ipos`` is the slot position
of ``ind`` in the ``icomp``-th component tensor.
``args[2]`` list of tuples representing dummy indices.
``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant
dummy index is the ``ipos1``-th slot position in the ``icomp1``-th
component tensor; the corresponding covariant index is
in the ``ipos2`` slot position in the ``icomp2``-th component tensor.
"""
identity = S.One
_index_structure = None # type: _IndexStructure
def __new__(cls, *args, **kw_args):
is_canon_bp = kw_args.get('is_canon_bp', False)
args = list(map(_sympify, args))
"""
If the internal dummy indices in one arg conflict with the free indices
of the remaining args, we need to rename those internal dummy indices.
"""
free = [get_free_indices(arg) for arg in args]
free = set(itertools.chain(*free)) #flatten free
newargs = []
for arg in args:
dum_this = set(get_dummy_indices(arg))
dum_other = [get_dummy_indices(a) for a in newargs]
dum_other = set(itertools.chain(*dum_other)) #flatten dum_other
free_this = set(get_free_indices(arg))
if len(dum_this.intersection(free)) > 0:
exclude = free_this.union(free, dum_other)
newarg = TensMul._dedupe_indices(arg, exclude)
else:
newarg = arg
newargs.append(newarg)
args = newargs
# Flatten:
args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])]
args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False)
# Data for indices:
index_types = [i.tensor_index_type for i in indices]
index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
obj = TensExpr.__new__(cls, *args)
obj._indices = indices
obj._index_types = index_types[:]
obj._index_structure = index_structure
obj._free = index_structure.free[:]
obj._dum = index_structure.dum[:]
obj._free_indices = {x[0] for x in obj.free}
obj._rank = len(obj.free)
obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
obj._coeff = S.One
obj._is_canon_bp = is_canon_bp
return obj
index_types = property(lambda self: self._index_types)
free = property(lambda self: self._free)
dum = property(lambda self: self._dum)
free_indices = property(lambda self: self._free_indices)
rank = property(lambda self: self._rank)
ext_rank = property(lambda self: self._ext_rank)
@staticmethod
def _indices_to_free_dum(args_indices):
free2pos1 = {}
free2pos2 = {}
dummy_data = []
indices = []
# Notation for positions (to better understand the code):
# `pos1`: position in the `args`.
# `pos2`: position in the indices.
# Example:
# A(i, j)*B(k, m, n)*C(p)
# `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul).
# `pos2` of `n` is 4 because it's the fifth overall index.
# Counter for the index position wrt the whole expression:
pos2 = 0
for pos1, arg_indices in enumerate(args_indices):
for index in arg_indices:
if not isinstance(index, TensorIndex):
raise TypeError("expected TensorIndex")
if -index in free2pos1:
# Dummy index detected:
other_pos1 = free2pos1.pop(-index)
other_pos2 = free2pos2.pop(-index)
if index.is_up:
dummy_data.append((index, pos1, other_pos1, pos2, other_pos2))
else:
dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2))
indices.append(index)
elif index in free2pos1:
raise ValueError("Repeated index: %s" % index)
else:
free2pos1[index] = pos1
free2pos2[index] = pos2
indices.append(index)
pos2 += 1
free = list(free2pos2.items())
free_names = [i.name for i in free2pos2.keys()]
dummy_data.sort(key=lambda x: x[3])
return indices, free, free_names, dummy_data
@staticmethod
def _dummy_data_to_dum(dummy_data):
return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data]
@staticmethod
def _tensMul_contract_indices(args, replace_indices=True):
replacements = [{} for _ in args]
#_index_order = all(_has_index_order(arg) for arg in args)
args_indices = [get_indices(arg) for arg in args]
indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
cdt = defaultdict(int)
def dummy_name_gen(tensor_index_type):
nd = str(cdt[tensor_index_type])
cdt[tensor_index_type] += 1
return tensor_index_type.dummy_name + '_' + nd
if replace_indices:
for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data:
index_type = old_index.tensor_index_type
while True:
dummy_name = dummy_name_gen(index_type)
if dummy_name not in free_names:
break
dummy = TensorIndex(dummy_name, index_type, True)
replacements[pos1cov][old_index] = dummy
replacements[pos1contra][-old_index] = -dummy
indices[pos2cov] = dummy
indices[pos2contra] = -dummy
args = [
arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg
for arg, repl in zip(args, replacements)]
dum = TensMul._dummy_data_to_dum(dummy_data)
return args, indices, free, dum
@staticmethod
def _get_components_from_args(args):
"""
Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied
by one another.
"""
components = []
for arg in args:
if not isinstance(arg, TensExpr):
continue
if isinstance(arg, TensAdd):
continue
components.extend(arg.components)
return components
@staticmethod
def _rebuild_tensors_list(args, index_structure):
indices = index_structure.get_indices()
#tensors = [None for i in components] # pre-allocate list
ind_pos = 0
for i, arg in enumerate(args):
if not isinstance(arg, TensExpr):
continue
prev_pos = ind_pos
ind_pos += arg.ext_rank
args[i] = Tensor(arg.component, indices[prev_pos:ind_pos])
def doit(self, **hints):
is_canon_bp = self._is_canon_bp
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
"""
There may now be conflicts between dummy indices of different args
(each arg's doit method does not have any information about which
dummy indices are already used in the other args), so we
deduplicate them.
"""
rule = dict(zip(self.args, args))
rule = self._dedupe_indices_in_rule(rule)
args = [rule[a] for a in self.args]
else:
args = self.args
args = [arg for arg in args if arg != self.identity]
# Extract non-tensor coefficients:
coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One)
args = [arg for arg in args if isinstance(arg, TensExpr)]
if len(args) == 0:
return coeff
if coeff != self.identity:
args = [coeff] + args
if coeff == 0:
return S.Zero
if len(args) == 1:
return args[0]
args, indices, free, dum = TensMul._tensMul_contract_indices(args)
# Data for indices:
index_types = [i.tensor_index_type for i in indices]
index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
obj = self.func(*args)
obj._index_types = index_types
obj._index_structure = index_structure
obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
obj._coeff = coeff
obj._is_canon_bp = is_canon_bp
return obj
# TODO: this method should be private
# TODO: should this method be renamed _from_components_free_dum ?
@staticmethod
def from_data(coeff, components, free, dum, **kw_args):
return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit()
@staticmethod
def _get_tensors_from_components_free_dum(components, free, dum):
"""
Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``.
"""
index_structure = _IndexStructure.from_components_free_dum(components, free, dum)
indices = index_structure.get_indices()
tensors = [None for i in components] # pre-allocate list
# distribute indices on components to build a list of tensors:
ind_pos = 0
for i, component in enumerate(components):
prev_pos = ind_pos
ind_pos += component.rank
tensors[i] = Tensor(component, indices[prev_pos:ind_pos])
return tensors
def _get_free_indices_set(self):
return {i[0] for i in self.free}
def _get_dummy_indices_set(self):
dummy_pos = set(itertools.chain(*self.dum))
return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos}
def _get_position_offset_for_indices(self):
arg_offset = [None for i in range(self.ext_rank)]
counter = 0
for arg in self.args:
if not isinstance(arg, TensExpr):
continue
for j in range(arg.ext_rank):
arg_offset[j + counter] = counter
counter += arg.ext_rank
return arg_offset
@property
def free_args(self):
return sorted([x[0] for x in self.free])
@property
def components(self):
return self._get_components_from_args(self.args)
@property
def free_in_args(self):
arg_offset = self._get_position_offset_for_indices()
argpos = self._get_indices_to_args_pos()
return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free]
@property
def coeff(self):
# return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)])
return self._coeff
@property
def nocoeff(self):
return self.func(*[t for t in self.args if isinstance(t, TensExpr)]).doit()
@property
def dum_in_args(self):
arg_offset = self._get_position_offset_for_indices()
argpos = self._get_indices_to_args_pos()
return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum]
def equals(self, other):
if other == 0:
return self.coeff == 0
other = _sympify(other)
if not isinstance(other, TensExpr):
assert not self.components
return self.coeff == other
return self.canon_bp() == other.canon_bp()
def get_indices(self):
"""
Returns the list of indices of the tensor.
Explanation
===========
The indices are listed in the order in which they appear in the
component tensors.
The dummy indices are given a name which does not collide with
the names of the free indices.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
>>> g = Lorentz.metric
>>> p, q = tensor_heads('p,q', [Lorentz])
>>> t = p(m1)*g(m0,m2)
>>> t.get_indices()
[m1, m0, m2]
>>> t2 = p(m1)*g(-m1, m2)
>>> t2.get_indices()
[L_0, -L_0, m2]
"""
return self._indices
def get_free_indices(self) -> list[TensorIndex]:
"""
Returns the list of free indices of the tensor.
Explanation
===========
The indices are listed in the order in which they appear in the
component tensors.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
>>> g = Lorentz.metric
>>> p, q = tensor_heads('p,q', [Lorentz])
>>> t = p(m1)*g(m0,m2)
>>> t.get_free_indices()
[m1, m0, m2]
>>> t2 = p(m1)*g(-m1, m2)
>>> t2.get_free_indices()
[m2]
"""
return self._index_structure.get_free_indices()
def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args])
def split(self):
"""
Returns a list of tensors, whose product is ``self``.
Explanation
===========
Dummy indices contracted among different tensor components
become free indices with the same name as the one used to
represent the dummy indices.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
>>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
>>> t = A(a,b)*B(-b,c)
>>> t
A(a, L_0)*B(-L_0, c)
>>> t.split()
[A(a, L_0), B(-L_0, c)]
"""
if self.args == ():
return [self]
splitp = []
res = 1
for arg in self.args:
if isinstance(arg, Tensor):
splitp.append(res*arg)
res = 1
else:
res *= arg
return splitp
def _expand(self, **hints):
# TODO: temporary solution, in the future this should be linked to
# `Expr.expand`.
args = [_expand(arg, **hints) for arg in self.args]
args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in args]
return TensAdd(*[
TensMul(*i) for i in itertools.product(*args1)]
)
def __neg__(self):
return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit()
def __getitem__(self, item):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
return self.data[item]
def _get_args_for_traditional_printer(self):
args = list(self.args)
if self.coeff.could_extract_minus_sign():
# expressions like "-A(a)"
sign = "-"
if args[0] == S.NegativeOne:
args = args[1:]
else:
args[0] = -args[0]
else:
sign = ""
return sign, args
def _sort_args_for_sorted_components(self):
"""
Returns the ``args`` sorted according to the components commutation
properties.
Explanation
===========
The sorting is done taking into account the commutation group
of the component tensors.
"""
cv = [arg for arg in self.args if isinstance(arg, TensExpr)]
sign = 1
n = len(cv) - 1
for i in range(n):
for j in range(n, i, -1):
c = cv[j-1].commutes_with(cv[j])
# if `c` is `None`, it does neither commute nor anticommute, skip:
if c not in (0, 1):
continue
typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name)
typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name)
if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name):
cv[j-1], cv[j] = cv[j], cv[j-1]
# if `c` is 1, the anticommute, so change sign:
if c:
sign = -sign
coeff = sign * self.coeff
if coeff != 1:
return [coeff] + cv
return cv
def sorted_components(self):
"""
Returns a tensor product with sorted components.
"""
return TensMul(*self._sort_args_for_sorted_components()).doit()
def perm2tensor(self, g, is_canon_bp=False):
"""
Returns the tensor corresponding to the permutation ``g``
For further details, see the method in ``TIDS`` with the same name.
"""
return perm2tensor(self, g, is_canon_bp=is_canon_bp)
def canon_bp(self):
"""
Canonicalize using the Butler-Portugal algorithm for canonicalization
under monoterm symmetries.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
>>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
>>> t = A(m0,-m1)*A(m1,-m0)
>>> t.canon_bp()
-A(L_0, L_1)*A(-L_0, -L_1)
>>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0)
>>> t.canon_bp()
0
"""
if self._is_canon_bp:
return self
expr = self.expand()
if isinstance(expr, TensAdd):
return expr.canon_bp()
if not expr.components:
return expr
t = expr.sorted_components()
g, dummies, msym = t._index_structure.indices_canon_args()
v = components_canon_args(t.components)
can = canonicalize(g, dummies, msym, *v)
if can == 0:
return S.Zero
tmul = t.perm2tensor(can, True)
return tmul
def contract_delta(self, delta):
t = self.contract_metric(delta)
return t
def _get_indices_to_args_pos(self):
"""
Get a dict mapping the index position to TensMul's argument number.
"""
pos_map = {}
pos_counter = 0
for arg_i, arg in enumerate(self.args):
if not isinstance(arg, TensExpr):
continue
assert isinstance(arg, Tensor)
for i in range(arg.ext_rank):
pos_map[pos_counter] = arg_i
pos_counter += 1
return pos_map
def contract_metric(self, g):
"""
Raise or lower indices with the metric ``g``.
Parameters
==========
g : metric
Notes
=====
See the ``TensorIndexType`` docstring for the contraction conventions.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
>>> g = Lorentz.metric
>>> p, q = tensor_heads('p,q', [Lorentz])
>>> t = p(m0)*q(m1)*g(-m0, -m1)
>>> t.canon_bp()
metric(L_0, L_1)*p(-L_0)*q(-L_1)
>>> t.contract_metric(g).canon_bp()
p(L_0)*q(-L_0)
"""
expr = self.expand()
if self != expr:
expr = canon_bp(expr)
return contract_metric(expr, g)
pos_map = self._get_indices_to_args_pos()
args = list(self.args)
#antisym = g.index_types[0].metric_antisym
if g.symmetry == TensorSymmetry.fully_symmetric(-2):
antisym = 1
elif g.symmetry == TensorSymmetry.fully_symmetric(2):
antisym = 0
elif g.symmetry == TensorSymmetry.no_symmetry(2):
antisym = None
else:
raise NotImplementedError
# list of positions of the metric ``g`` inside ``args``
gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g]
if not gpos:
return self
# Sign is either 1 or -1, to correct the sign after metric contraction
# (for spinor indices).
sign = 1
dum = self.dum[:]
free = self.free[:]
elim = set()
for gposx in gpos:
if gposx in elim:
continue
free1 = [x for x in free if pos_map[x[1]] == gposx]
dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx]
if not dum1:
continue
elim.add(gposx)
# subs with the multiplication neutral element, that is, remove it:
args[gposx] = 1
if len(dum1) == 2:
if not antisym:
dum10, dum11 = dum1
if pos_map[dum10[1]] == gposx:
# the index with pos p0 contravariant
p0 = dum10[0]
else:
# the index with pos p0 is covariant
p0 = dum10[1]
if pos_map[dum11[1]] == gposx:
# the index with pos p1 is contravariant
p1 = dum11[0]
else:
# the index with pos p1 is covariant
p1 = dum11[1]
dum.append((p0, p1))
else:
dum10, dum11 = dum1
# change the sign to bring the indices of the metric to contravariant
# form; change the sign if dum10 has the metric index in position 0
if pos_map[dum10[1]] == gposx:
# the index with pos p0 is contravariant
p0 = dum10[0]
if dum10[1] == 1:
sign = -sign
else:
# the index with pos p0 is covariant
p0 = dum10[1]
if dum10[0] == 0:
sign = -sign
if pos_map[dum11[1]] == gposx:
# the index with pos p1 is contravariant
p1 = dum11[0]
sign = -sign
else:
# the index with pos p1 is covariant
p1 = dum11[1]
dum.append((p0, p1))
elif len(dum1) == 1:
if not antisym:
dp0, dp1 = dum1[0]
if pos_map[dp0] == pos_map[dp1]:
# g(i, -i)
typ = g.index_types[0]
sign = sign*typ.dim
else:
# g(i0, i1)*p(-i1)
if pos_map[dp0] == gposx:
p1 = dp1
else:
p1 = dp0
ind, p = free1[0]
free.append((ind, p1))
else:
dp0, dp1 = dum1[0]
if pos_map[dp0] == pos_map[dp1]:
# g(i, -i)
typ = g.index_types[0]
sign = sign*typ.dim
if dp0 < dp1:
# g(i, -i) = -D with antisymmetric metric
sign = -sign
else:
# g(i0, i1)*p(-i1)
if pos_map[dp0] == gposx:
p1 = dp1
if dp0 == 0:
sign = -sign
else:
p1 = dp0
ind, p = free1[0]
free.append((ind, p1))
dum = [x for x in dum if x not in dum1]
free = [x for x in free if x not in free1]
# shift positions:
shift = 0
shifts = [0]*len(args)
for i in range(len(args)):
if i in elim:
shift += 2
continue
shifts[i] = shift
free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim]
dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for p0, p1 in dum if pos_map[p0] not in elim and pos_map[p1] not in elim]
res = sign*TensMul(*args).doit()
if not isinstance(res, TensExpr):
return res
im = _IndexStructure.from_components_free_dum(res.components, free, dum)
return res._set_new_index_structure(im)
def _set_new_index_structure(self, im, is_canon_bp=False):
indices = im.get_indices()
return self._set_indices(*indices, is_canon_bp=is_canon_bp)
def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
if len(indices) != self.ext_rank:
raise ValueError("indices length mismatch")
args = list(self.args)[:]
pos = 0
for i, arg in enumerate(args):
if not isinstance(arg, TensExpr):
continue
assert isinstance(arg, Tensor)
ext_rank = arg.ext_rank
args[i] = arg._set_indices(*indices[pos:pos+ext_rank])
pos += ext_rank
return TensMul(*args, is_canon_bp=is_canon_bp).doit()
@staticmethod
def _index_replacement_for_contract_metric(args, free, dum):
for arg in args:
if not isinstance(arg, TensExpr):
continue
assert isinstance(arg, Tensor)
def substitute_indices(self, *index_tuples):
new_args = []
for arg in self.args:
if isinstance(arg, TensExpr):
arg = arg.substitute_indices(*index_tuples)
new_args.append(arg)
return TensMul(*new_args).doit()
def __call__(self, *indices):
deprecate_call()
free_args = self.free_args
indices = list(indices)
if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
raise ValueError('incompatible types')
if indices == free_args:
return self
t = self.substitute_indices(*list(zip(free_args, indices)))
# object is rebuilt in order to make sure that all contracted indices
# get recognized as dummies, but only if there are contracted indices.
if len({i if i.is_up else -i for i in indices}) != len(indices):
return t.func(*t.args)
return t
def _extract_data(self, replacement_dict):
args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)])
coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One)
indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
dum = TensMul._dummy_data_to_dum(dummy_data)
ext_rank = self.ext_rank
free.sort(key=lambda x: x[1])
free_indices = [i[0] for i in free]
return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank)
@property
def data(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
dat = _tensor_data_substitution_dict[self.expand()]
return dat
@data.setter
def data(self, data):
deprecate_data()
raise ValueError("Not possible to set component data to a tensor expression")
@data.deleter
def data(self):
deprecate_data()
raise ValueError("Not possible to delete component data to a tensor expression")
def __iter__(self):
deprecate_data()
with ignore_warnings(SymPyDeprecationWarning):
if self.data is None:
raise ValueError("No iteration on abstract tensors")
return self.data.__iter__()
@staticmethod
def _dedupe_indices(new, exclude):
"""
exclude: set
new: TensExpr
If ``new`` has any dummy indices that are in ``exclude``, return a version
of new with those indices replaced. If no replacements are needed,
return None
"""
exclude = set(exclude)
dums_new = set(get_dummy_indices(new))
free_new = set(get_free_indices(new))
conflicts = dums_new.intersection(exclude)
if len(conflicts) == 0:
return None
"""
``exclude_for_gen`` is to be passed to ``_IndexStructure._get_generator_for_dummy_indices()``.
Since the latter does not use the index position for anything, we just
set it as ``None`` here.
"""
exclude.update(dums_new)
exclude.update(free_new)
exclude_for_gen = [(i, None) for i in exclude]
gen = _IndexStructure._get_generator_for_dummy_indices(exclude_for_gen)
repl = {}
for d in conflicts:
if -d in repl.keys():
continue
newname = gen(d.tensor_index_type)
new_d = d.func(newname, *d.args[1:])
repl[d] = new_d
repl[-d] = -new_d
if len(repl) == 0:
return None
new_renamed = new._replace_indices(repl)
return new_renamed
def _dedupe_indices_in_rule(self, rule):
"""
rule: dict
This applies TensMul._dedupe_indices on all values of rule.
"""
index_rules = {k:v for k,v in rule.items() if isinstance(k, TensorIndex)}
other_rules = {k:v for k,v in rule.items() if k not in index_rules.keys()}
exclude = set(self.get_indices())
newrule = {}
newrule.update(index_rules)
exclude.update(index_rules.keys())
exclude.update(index_rules.values())
for old, new in other_rules.items():
new_renamed = TensMul._dedupe_indices(new, exclude)
if old == new or new_renamed is None:
newrule[old] = new
else:
newrule[old] = new_renamed
exclude.update(get_indices(new_renamed))
return newrule
def _eval_rewrite_as_Indexed(self, *args, **kwargs):
from sympy.concrete.summations import Sum
index_symbols = [i.args[0] for i in self.get_indices()]
args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args]
expr = Mul.fromiter(args)
return self._check_add_Sum(expr, index_symbols)
def _eval_partial_derivative(self, s):
# Evaluation like Mul
terms = []
for i, arg in enumerate(self.args):
# checking whether some tensor instance is differentiated
# or some other thing is necessary, but ugly
if isinstance(arg, TensExpr):
d = arg._eval_partial_derivative(s)
else:
# do not call diff is s is no symbol
if s._diff_wrt:
d = arg._eval_derivative(s)
else:
d = S.Zero
if d:
terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:]))
return TensAdd.fromiter(terms)
class TensorElement(TensExpr):
"""
Tensor with evaluated components.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
>>> from sympy import symbols
>>> L = TensorIndexType("L")
>>> i, j, k = symbols("i j k")
>>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2))
>>> A(i, j).get_free_indices()
[i, j]
If we want to set component ``i`` to a specific value, use the
``TensorElement`` class:
>>> from sympy.tensor.tensor import TensorElement
>>> te = TensorElement(A(i, j), {i: 2})
As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd
element), the free indices will only contain ``j``:
>>> te.get_free_indices()
[j]
"""
def __new__(cls, expr, index_map):
if not isinstance(expr, Tensor):
# remap
if not isinstance(expr, TensExpr):
raise TypeError("%s is not a tensor expression" % expr)
return expr.func(*[TensorElement(arg, index_map) for arg in expr.args])
expr_free_indices = expr.get_free_indices()
name_translation = {i.args[0]: i for i in expr_free_indices}
index_map = {name_translation.get(index, index): value for index, value in index_map.items()}
index_map = {index: value for index, value in index_map.items() if index in expr_free_indices}
if len(index_map) == 0:
return expr
free_indices = [i for i in expr_free_indices if i not in index_map.keys()]
index_map = Dict(index_map)
obj = TensExpr.__new__(cls, expr, index_map)
obj._free_indices = free_indices
return obj
@property
def free(self):
return [(index, i) for i, index in enumerate(self.get_free_indices())]
@property
def dum(self):
# TODO: inherit dummies from expr
return []
@property
def expr(self):
return self._args[0]
@property
def index_map(self):
return self._args[1]
@property
def coeff(self):
return S.One
@property
def nocoeff(self):
return self
def get_free_indices(self):
return self._free_indices
def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
# TODO: can be improved:
return self.xreplace(repl)
def get_indices(self):
return self.get_free_indices()
def _extract_data(self, replacement_dict):
ret_indices, array = self.expr._extract_data(replacement_dict)
index_map = self.index_map
slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices)
ret_indices = [i for i in ret_indices if i not in index_map]
array = array.__getitem__(slice_tuple)
return ret_indices, array
class WildTensorHead(TensorHead):
"""
A wild object that is used to create ``WildTensor`` instances
Explanation
===========
Examples
========
>>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType
>>> R3 = TensorIndexType('R3', dim=3)
>>> p = TensorIndex('p', R3)
>>> q = TensorIndex('q', R3)
A WildTensorHead can be created without specifying a ``TensorIndexType``
>>> W = WildTensorHead("W")
Calling it with a ``TensorIndex`` creates a ``WildTensor`` instance.
>>> type(W(p))
<class 'sympy.tensor.tensor.WildTensor'>
The ``TensorIndexType`` is automatically detected from the index that is passed
>>> W(p).component
W(R3)
Calling it with no indices returns an object that can match tensors with any number of indices.
>>> K = TensorHead('K', [R3])
>>> Q = TensorHead('Q', [R3, R3])
>>> W().matches(K(p))
{W: K(p)}
>>> W().matches(Q(p,q))
{W: Q(p, q)}
If you want to ignore the order of indices while matching, pass ``unordered_indices=True``.
>>> U = WildTensorHead("U", unordered_indices=True)
>>> W(p,q).matches(Q(q,p))
>>> U(p,q).matches(Q(q,p))
{U(R3,R3): _WildTensExpr(Q(q, p))}
Parameters
==========
name : name of the tensor
unordered_indices : whether the order of the indices matters for matching
(default: False)
See also
========
``WildTensor``
``TensorHead``
"""
def __new__(cls, name, index_types=None, symmetry=None, comm=0, unordered_indices=False):
if isinstance(name, str):
name_symbol = Symbol(name)
elif isinstance(name, Symbol):
name_symbol = name
else:
raise ValueError("invalid name")
if index_types is None:
index_types = []
if symmetry is None:
symmetry = TensorSymmetry.no_symmetry(len(index_types))
else:
assert symmetry.rank == len(index_types)
if symmetry != TensorSymmetry.no_symmetry(len(index_types)):
raise NotImplementedError("Wild matching based on symmetry is not implemented.")
obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), sympify(symmetry), sympify(comm), sympify(unordered_indices))
return obj
@property
def unordered_indices(self):
return self.args[4]
def __call__(self, *indices, **kwargs):
tensor = WildTensor(self, indices, **kwargs)
return tensor.doit()
class WildTensor(Tensor):
"""
A wild object which matches ``Tensor`` instances
Explanation
===========
This is instantiated by attaching indices to a ``WildTensorHead`` instance.
Examples
========
>>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType
>>> W = WildTensorHead("W")
>>> R3 = TensorIndexType('R3', dim=3)
>>> p = TensorIndex('p', R3)
>>> q = TensorIndex('q', R3)
>>> K = TensorHead('K', [R3])
>>> Q = TensorHead('Q', [R3, R3])
Matching also takes the indices into account
>>> W(p).matches(K(p))
{W(R3): _WildTensExpr(K(p))}
>>> W(p).matches(K(q))
>>> W(p).matches(K(-p))
If you want to match objects with any number of indices, just use a ``WildTensor`` with no indices.
>>> W().matches(K(p))
{W: K(p)}
>>> W().matches(Q(p,q))
{W: Q(p, q)}
See Also
========
``WildTensorHead``
``Tensor``
"""
def __new__(cls, tensor_head, indices, **kw_args):
is_canon_bp = kw_args.pop("is_canon_bp", False)
if tensor_head.func == TensorHead:
"""
If someone tried to call WildTensor by supplying a TensorHead (not a WildTensorHead), return a normal tensor instead. This is helpful when using subs on an expression to replace occurrences of a WildTensorHead with a TensorHead.
"""
return Tensor(tensor_head, indices, is_canon_bp=is_canon_bp, **kw_args)
elif tensor_head.func == _WildTensExpr:
return tensor_head(*indices)
indices = cls._parse_indices(tensor_head, indices)
index_types = [ind.tensor_index_type for ind in indices]
tensor_head = tensor_head.func(
tensor_head.name,
index_types,
symmetry=None,
comm=tensor_head.comm,
unordered_indices=tensor_head.unordered_indices,
)
obj = Basic.__new__(cls, tensor_head, Tuple(*indices))
obj.name = tensor_head.name
obj._index_structure = _IndexStructure.from_indices(*indices)
obj._free = obj._index_structure.free[:]
obj._dum = obj._index_structure.dum[:]
obj._ext_rank = obj._index_structure._ext_rank
obj._coeff = S.One
obj._nocoeff = obj
obj._component = tensor_head
obj._components = [tensor_head]
if tensor_head.rank != len(indices):
raise ValueError("wrong number of indices")
obj.is_canon_bp = is_canon_bp
obj._index_map = obj._build_index_map(indices, obj._index_structure)
return obj
def matches(self, expr, repl_dict=None, old=False):
if not isinstance(expr, TensExpr) and expr != S(1):
return None
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
if len(self.indices) > 0:
if not hasattr(expr, "get_free_indices"):
return None
expr_indices = expr.get_free_indices()
if len(expr_indices) != len(self.indices):
return None
if self._component.unordered_indices:
m = self._match_indices_ignoring_order(expr)
if m is None:
return None
else:
repl_dict.update(m)
else:
for i in range(len(expr_indices)):
m = self.indices[i].matches(expr_indices[i])
if m is None:
return None
else:
repl_dict.update(m)
repl_dict[self.component] = _WildTensExpr(expr)
else:
#If no indices were passed to the WildTensor, it may match tensors with any number of indices.
repl_dict[self] = expr
return repl_dict
def _match_indices_ignoring_order(self, expr, repl_dict=None, old=False):
"""
Helper method for matches. Checks if the indices of self and expr
match disregarding index ordering.
"""
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
def siftkey(ind):
if isinstance(ind, WildTensorIndex):
if ind.ignore_updown:
return "wild, updown"
else:
return "wild"
else:
return "nonwild"
indices_sifted = sift(self.indices, siftkey)
matched_indices = []
expr_indices_remaining = expr.get_indices()
for ind in indices_sifted["nonwild"]:
matched_this_ind = False
for e_ind in expr_indices_remaining:
if e_ind in matched_indices:
continue
m = ind.matches(e_ind)
if m is not None:
matched_this_ind = True
repl_dict.update(m)
matched_indices.append(e_ind)
break
if not matched_this_ind:
return None
expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices]
for ind in indices_sifted["wild"]:
matched_this_ind = False
for e_ind in expr_indices_remaining:
m = ind.matches(e_ind)
if m is not None:
if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]:
return None
matched_this_ind = True
repl_dict.update(m)
matched_indices.append(e_ind)
break
if not matched_this_ind:
return None
expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices]
for ind in indices_sifted["wild, updown"]:
matched_this_ind = False
for e_ind in expr_indices_remaining:
m = ind.matches(e_ind)
if m is not None:
if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]:
return None
matched_this_ind = True
repl_dict.update(m)
matched_indices.append(e_ind)
break
if not matched_this_ind:
return None
if len(matched_indices) < len(self.indices):
return None
else:
return repl_dict
class WildTensorIndex(TensorIndex):
"""
A wild object that matches TensorIndex instances.
Examples
========
>>> from sympy.tensor.tensor import TensorIndex, TensorIndexType, WildTensorIndex
>>> R3 = TensorIndexType('R3', dim=3)
>>> p = TensorIndex("p", R3)
By default, covariant indices only match with covariant indices (and
similarly for contravariant)
>>> q = WildTensorIndex("q", R3)
>>> (q).matches(p)
{q: p}
>>> (q).matches(-p)
If you want matching to ignore whether the index is co/contra-variant, set
ignore_updown=True
>>> r = WildTensorIndex("r", R3, ignore_updown=True)
>>> (r).matches(-p)
{r: -p}
>>> (r).matches(p)
{r: p}
Parameters
==========
name : name of the index (string), or ``True`` if you want it to be
automatically assigned
tensor_index_type : ``TensorIndexType`` of the index
is_up : flag for contravariant index (is_up=True by default)
ignore_updown : bool, Whether this should match both co- and contra-variant
indices (default:False)
"""
def __new__(cls, name, tensor_index_type, is_up=True, ignore_updown=False):
if isinstance(name, str):
name_symbol = Symbol(name)
elif isinstance(name, Symbol):
name_symbol = name
elif name is True:
name = "_i{}".format(len(tensor_index_type._autogenerated))
name_symbol = Symbol(name)
tensor_index_type._autogenerated.append(name_symbol)
else:
raise ValueError("invalid name")
is_up = sympify(is_up)
ignore_updown = sympify(ignore_updown)
return Basic.__new__(cls, name_symbol, tensor_index_type, is_up, ignore_updown)
@property
def ignore_updown(self):
return self.args[3]
def __neg__(self):
t1 = WildTensorIndex(self.name, self.tensor_index_type,
(not self.is_up), self.ignore_updown)
return t1
def matches(self, expr, repl_dict=None, old=False):
if not isinstance(expr, TensorIndex):
return None
if self.tensor_index_type != expr.tensor_index_type:
return None
if not self.ignore_updown:
if self.is_up != expr.is_up:
return None
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
repl_dict[self] = expr
return repl_dict
class _WildTensExpr(Basic):
"""
INTERNAL USE ONLY
This is an object that helps with replacement of WildTensors in expressions.
When this object is set as the tensor_head of a WildTensor, it replaces the
WildTensor by a TensExpr (passed when initializing this object).
Examples
========
>>> from sympy.tensor.tensor import WildTensorHead, TensorIndex, TensorHead, TensorIndexType
>>> W = WildTensorHead("W")
>>> R3 = TensorIndexType('R3', dim=3)
>>> p = TensorIndex('p', R3)
>>> q = TensorIndex('q', R3)
>>> K = TensorHead('K', [R3])
>>> print( ( K(p) ).replace( W(p), W(q)*W(-q)*W(p) ) )
K(R_0)*K(-R_0)*K(p)
"""
def __init__(self, expr):
if not isinstance(expr, TensExpr):
raise TypeError("_WildTensExpr expects a TensExpr as argument")
self.expr = expr
def __call__(self, *indices):
return self.expr._replace_indices(dict(zip(self.expr.get_free_indices(), indices)))
def __neg__(self):
return self.func(self.expr*S.NegativeOne)
def __abs__(self):
raise NotImplementedError
def __add__(self, other):
if other.func != self.func:
raise TypeError(f"Cannot add {self.func} to {other.func}")
return self.func(self.expr+other.expr)
def __radd__(self, other):
if other.func != self.func:
raise TypeError(f"Cannot add {self.func} to {other.func}")
return self.func(other.expr+self.expr)
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return other + (-self)
def __mul__(self, other):
raise NotImplementedError
def __rmul__(self, other):
raise NotImplementedError
def __truediv__(self, other):
raise NotImplementedError
def __rtruediv__(self, other):
raise NotImplementedError
def __pow__(self, other):
raise NotImplementedError
def __rpow__(self, other):
raise NotImplementedError
def canon_bp(p):
"""
Butler-Portugal canonicalization. See ``tensor_can.py`` from the
combinatorics module for the details.
"""
if isinstance(p, TensExpr):
return p.canon_bp()
return p
def tensor_mul(*a):
"""
product of tensors
"""
if not a:
return TensMul.from_data(S.One, [], [], [])
t = a[0]
for tx in a[1:]:
t = t*tx
return t
def riemann_cyclic_replace(t_r):
"""
replace Riemann tensor with an equivalent expression
``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)``
"""
free = sorted(t_r.free, key=lambda x: x[1])
m, n, p, q = [x[0] for x in free]
t0 = t_r*Rational(2, 3)
t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3)
t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3)
t3 = t0 + t1 + t2
return t3
def riemann_cyclic(t2):
"""
Replace each Riemann tensor with an equivalent expression
satisfying the cyclic identity.
This trick is discussed in the reference guide to Cadabra.
Examples
========
>>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry
>>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
>>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
>>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
>>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
>>> riemann_cyclic(t)
0
"""
t2 = t2.expand()
if isinstance(t2, (TensMul, Tensor)):
args = [t2]
else:
args = t2.args
a1 = [x.split() for x in args]
a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1]
a3 = [tensor_mul(*v) for v in a2]
t3 = TensAdd(*a3).doit()
if not t3:
return t3
else:
return canon_bp(t3)
def get_lines(ex, index_type):
"""
Returns ``(lines, traces, rest)`` for an index type,
where ``lines`` is the list of list of positions of a matrix line,
``traces`` is the list of list of traced matrix lines,
``rest`` is the rest of the elements of the tensor.
"""
def _join_lines(a):
i = 0
while i < len(a):
x = a[i]
xend = x[-1]
xstart = x[0]
hit = True
while hit:
hit = False
for j in range(i + 1, len(a)):
if j >= len(a):
break
if a[j][0] == xend:
hit = True
x.extend(a[j][1:])
xend = x[-1]
a.pop(j)
continue
if a[j][0] == xstart:
hit = True
a[i] = reversed(a[j][1:]) + x
x = a[i]
xstart = a[i][0]
a.pop(j)
continue
if a[j][-1] == xend:
hit = True
x.extend(reversed(a[j][:-1]))
xend = x[-1]
a.pop(j)
continue
if a[j][-1] == xstart:
hit = True
a[i] = a[j][:-1] + x
x = a[i]
xstart = x[0]
a.pop(j)
continue
i += 1
return a
arguments = ex.args
dt = {}
for c in ex.args:
if not isinstance(c, TensExpr):
continue
if c in dt:
continue
index_types = c.index_types
a = []
for i in range(len(index_types)):
if index_types[i] is index_type:
a.append(i)
if len(a) > 2:
raise ValueError('at most two indices of type %s allowed' % index_type)
if len(a) == 2:
dt[c] = a
#dum = ex.dum
lines = []
traces = []
traces1 = []
#indices_to_args_pos = ex._get_indices_to_args_pos()
# TODO: add a dum_to_components_map ?
for p0, p1, c0, c1 in ex.dum_in_args:
if arguments[c0] not in dt:
continue
if c0 == c1:
traces.append([c0])
continue
ta0 = dt[arguments[c0]]
ta1 = dt[arguments[c1]]
if p0 not in ta0:
continue
if ta0.index(p0) == ta1.index(p1):
# case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1;
# to deal with this case one could add to the position
# a flag for transposition;
# one could write [(c0, False), (c1, True)]
raise NotImplementedError
# if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1
# if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0
ta0 = dt[arguments[c0]]
b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0)
lines1 = lines[:]
for line in lines:
if line[-1] == b0:
if line[0] == b1:
n = line.index(min(line))
traces1.append(line)
traces.append(line[n:] + line[:n])
else:
line.append(b1)
break
elif line[0] == b1:
line.insert(0, b0)
break
else:
lines1.append([b0, b1])
lines = [x for x in lines1 if x not in traces1]
lines = _join_lines(lines)
rest = []
for line in lines:
for y in line:
rest.append(y)
for line in traces:
for y in line:
rest.append(y)
rest = [x for x in range(len(arguments)) if x not in rest]
return lines, traces, rest
def get_free_indices(t):
if not isinstance(t, TensExpr):
return ()
return t.get_free_indices()
def get_indices(t):
if not isinstance(t, TensExpr):
return ()
return t.get_indices()
def get_dummy_indices(t):
if not isinstance(t, TensExpr):
return ()
inds = t.get_indices()
free = t.get_free_indices()
return [i for i in inds if i not in free]
def get_index_structure(t):
if isinstance(t, TensExpr):
return t._index_structure
return _IndexStructure([], [], [], [])
def get_coeff(t):
if isinstance(t, Tensor):
return S.One
if isinstance(t, TensMul):
return t.coeff
if isinstance(t, TensExpr):
raise ValueError("no coefficient associated to this tensor expression")
return t
def contract_metric(t, g):
if isinstance(t, TensExpr):
return t.contract_metric(g)
return t
def perm2tensor(t, g, is_canon_bp=False):
"""
Returns the tensor corresponding to the permutation ``g``
For further details, see the method in ``TIDS`` with the same name.
"""
if not isinstance(t, TensExpr):
return t
elif isinstance(t, (Tensor, TensMul)):
nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp)
res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp)
if g[-1] != len(g) - 1:
return -res
return res
raise NotImplementedError()
def substitute_indices(t, *index_tuples):
if not isinstance(t, TensExpr):
return t
return t.substitute_indices(*index_tuples)
def _expand(expr, **kwargs):
if isinstance(expr, TensExpr):
return expr._expand(**kwargs)
else:
return expr.expand(**kwargs)
def get_postprocessor(cls):
def _postprocessor(expr):
tens_class = {Mul: TensMul, Add: TensAdd}[cls]
if any(isinstance(a, TensExpr) for a in expr.args):
return tens_class(*expr.args)
else:
return expr
return _postprocessor
Basic._constructor_postprocessor_mapping[TensExpr] = {
"Mul": [get_postprocessor(Mul)],
}
|