1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878
|
\input texinfo @c -*-texinfo-*-
@c %**start of header
@setfilename ginac.info
@settitle GiNaC, an open framework for symbolic computation within the C++ programming language
@setchapternewpage on
@afourpaper
@c For `info' only.
@paragraphindent 0
@c For TeX only.
@iftex
@c I hate putting "@noindent" in front of every paragraph.
@parindent=0pt
@end iftex
@c %**end of header
@include version.texi
@dircategory Mathematics
@direntry
* ginac: (ginac). C++ library for symbolic computation.
@end direntry
@ifinfo
This is a tutorial that documents GiNaC @value{VERSION}, an open
framework for symbolic computation within the C++ programming language.
Copyright (C) 1999-2010 Johannes Gutenberg University Mainz, Germany
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
@end ifinfo
@finalout
@c finalout prevents ugly black rectangles on overfull hbox lines
@titlepage
@title GiNaC @value{VERSION}
@subtitle An open framework for symbolic computation within the C++ programming language
@subtitle @value{UPDATED}
@author @uref{http://www.ginac.de}
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1999-2010 Johannes Gutenberg University Mainz, Germany
@sp 2
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
@end titlepage
@page
@contents
@page
@node Top, Introduction, (dir), (dir)
@c node-name, next, previous, up
@top GiNaC
This is a tutorial that documents GiNaC @value{VERSION}, an open
framework for symbolic computation within the C++ programming language.
@menu
* Introduction:: GiNaC's purpose.
* A tour of GiNaC:: A quick tour of the library.
* Installation:: How to install the package.
* Basic concepts:: Description of fundamental classes.
* Methods and functions:: Algorithms for symbolic manipulations.
* Extending GiNaC:: How to extend the library.
* A comparison with other CAS:: Compares GiNaC to traditional CAS.
* Internal structures:: Description of some internal structures.
* Package tools:: Configuring packages to work with GiNaC.
* Bibliography::
* Concept index::
@end menu
@node Introduction, A tour of GiNaC, Top, Top
@c node-name, next, previous, up
@chapter Introduction
@cindex history of GiNaC
The motivation behind GiNaC derives from the observation that most
present day computer algebra systems (CAS) are linguistically and
semantically impoverished. Although they are quite powerful tools for
learning math and solving particular problems they lack modern
linguistic structures that allow for the creation of large-scale
projects. GiNaC is an attempt to overcome this situation by extending a
well established and standardized computer language (C++) by some
fundamental symbolic capabilities, thus allowing for integrated systems
that embed symbolic manipulations together with more established areas
of computer science (like computation-intense numeric applications,
graphical interfaces, etc.) under one roof.
The particular problem that led to the writing of the GiNaC framework is
still a very active field of research, namely the calculation of higher
order corrections to elementary particle interactions. There,
theoretical physicists are interested in matching present day theories
against experiments taking place at particle accelerators. The
computations involved are so complex they call for a combined symbolical
and numerical approach. This turned out to be quite difficult to
accomplish with the present day CAS we have worked with so far and so we
tried to fill the gap by writing GiNaC. But of course its applications
are in no way restricted to theoretical physics.
This tutorial is intended for the novice user who is new to GiNaC but
already has some background in C++ programming. However, since a
hand-made documentation like this one is difficult to keep in sync with
the development, the actual documentation is inside the sources in the
form of comments. That documentation may be parsed by one of the many
Javadoc-like documentation systems. If you fail at generating it you
may access it from @uref{http://www.ginac.de/reference/, the GiNaC home
page}. It is an invaluable resource not only for the advanced user who
wishes to extend the system (or chase bugs) but for everybody who wants
to comprehend the inner workings of GiNaC. This little tutorial on the
other hand only covers the basic things that are unlikely to change in
the near future.
@section License
The GiNaC framework for symbolic computation within the C++ programming
language is Copyright @copyright{} 1999-2010 Johannes Gutenberg
University Mainz, Germany.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
@node A tour of GiNaC, How to use it from within C++, Introduction, Top
@c node-name, next, previous, up
@chapter A Tour of GiNaC
This quick tour of GiNaC wants to arise your interest in the
subsequent chapters by showing off a bit. Please excuse us if it
leaves many open questions.
@menu
* How to use it from within C++:: Two simple examples.
* What it can do for you:: A Tour of GiNaC's features.
@end menu
@node How to use it from within C++, What it can do for you, A tour of GiNaC, A tour of GiNaC
@c node-name, next, previous, up
@section How to use it from within C++
The GiNaC open framework for symbolic computation within the C++ programming
language does not try to define a language of its own as conventional
CAS do. Instead, it extends the capabilities of C++ by symbolic
manipulations. Here is how to generate and print a simple (and rather
pointless) bivariate polynomial with some large coefficients:
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
int main()
@{
symbol x("x"), y("y");
ex poly;
for (int i=0; i<3; ++i)
poly += factorial(i+16)*pow(x,i)*pow(y,2-i);
cout << poly << endl;
return 0;
@}
@end example
Assuming the file is called @file{hello.cc}, on our system we can compile
and run it like this:
@example
$ c++ hello.cc -o hello -lcln -lginac
$ ./hello
355687428096000*x*y+20922789888000*y^2+6402373705728000*x^2
@end example
(@xref{Package tools}, for tools that help you when creating a software
package that uses GiNaC.)
@cindex Hermite polynomial
Next, there is a more meaningful C++ program that calls a function which
generates Hermite polynomials in a specified free variable.
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
ex HermitePoly(const symbol & x, int n)
@{
ex HKer=exp(-pow(x, 2));
// uses the identity H_n(x) == (-1)^n exp(x^2) (d/dx)^n exp(-x^2)
return normal(pow(-1, n) * diff(HKer, x, n) / HKer);
@}
int main()
@{
symbol z("z");
for (int i=0; i<6; ++i)
cout << "H_" << i << "(z) == " << HermitePoly(z,i) << endl;
return 0;
@}
@end example
When run, this will type out
@example
H_0(z) == 1
H_1(z) == 2*z
H_2(z) == 4*z^2-2
H_3(z) == -12*z+8*z^3
H_4(z) == -48*z^2+16*z^4+12
H_5(z) == 120*z-160*z^3+32*z^5
@end example
This method of generating the coefficients is of course far from optimal
for production purposes.
In order to show some more examples of what GiNaC can do we will now use
the @command{ginsh}, a simple GiNaC interactive shell that provides a
convenient window into GiNaC's capabilities.
@node What it can do for you, Installation, How to use it from within C++, A tour of GiNaC
@c node-name, next, previous, up
@section What it can do for you
@cindex @command{ginsh}
After invoking @command{ginsh} one can test and experiment with GiNaC's
features much like in other Computer Algebra Systems except that it does
not provide programming constructs like loops or conditionals. For a
concise description of the @command{ginsh} syntax we refer to its
accompanied man page. Suffice to say that assignments and comparisons in
@command{ginsh} are written as they are in C, i.e. @code{=} assigns and
@code{==} compares.
It can manipulate arbitrary precision integers in a very fast way.
Rational numbers are automatically converted to fractions of coprime
integers:
@example
> x=3^150;
369988485035126972924700782451696644186473100389722973815184405301748249
> y=3^149;
123329495011708990974900260817232214728824366796574324605061468433916083
> x/y;
3
> y/x;
1/3
@end example
Exact numbers are always retained as exact numbers and only evaluated as
floating point numbers if requested. For instance, with numeric
radicals is dealt pretty much as with symbols. Products of sums of them
can be expanded:
@example
> expand((1+a^(1/5)-a^(2/5))^3);
1+3*a+3*a^(1/5)-5*a^(3/5)-a^(6/5)
> expand((1+3^(1/5)-3^(2/5))^3);
10-5*3^(3/5)
> evalf((1+3^(1/5)-3^(2/5))^3);
0.33408977534118624228
@end example
The function @code{evalf} that was used above converts any number in
GiNaC's expressions into floating point numbers. This can be done to
arbitrary predefined accuracy:
@example
> evalf(1/7);
0.14285714285714285714
> Digits=150;
150
> evalf(1/7);
0.1428571428571428571428571428571428571428571428571428571428571428571428
5714285714285714285714285714285714285
@end example
Exact numbers other than rationals that can be manipulated in GiNaC
include predefined constants like Archimedes' @code{Pi}. They can both
be used in symbolic manipulations (as an exact number) as well as in
numeric expressions (as an inexact number):
@example
> a=Pi^2+x;
x+Pi^2
> evalf(a);
9.869604401089358619+x
> x=2;
2
> evalf(a);
11.869604401089358619
@end example
Built-in functions evaluate immediately to exact numbers if
this is possible. Conversions that can be safely performed are done
immediately; conversions that are not generally valid are not done:
@example
> cos(42*Pi);
1
> cos(acos(x));
x
> acos(cos(x));
acos(cos(x))
@end example
(Note that converting the last input to @code{x} would allow one to
conclude that @code{42*Pi} is equal to @code{0}.)
Linear equation systems can be solved along with basic linear
algebra manipulations over symbolic expressions. In C++ GiNaC offers
a matrix class for this purpose but we can see what it can do using
@command{ginsh}'s bracket notation to type them in:
@example
> lsolve(a+x*y==z,x);
y^(-1)*(z-a);
> lsolve(@{3*x+5*y == 7, -2*x+10*y == -5@}, @{x, y@});
@{x==19/8,y==-1/40@}
> M = [ [1, 3], [-3, 2] ];
[[1,3],[-3,2]]
> determinant(M);
11
> charpoly(M,lambda);
lambda^2-3*lambda+11
> A = [ [1, 1], [2, -1] ];
[[1,1],[2,-1]]
> A+2*M;
[[1,1],[2,-1]]+2*[[1,3],[-3,2]]
> evalm(%);
[[3,7],[-4,3]]
> B = [ [0, 0, a], [b, 1, -b], [-1/a, 0, 0] ];
> evalm(B^(2^12345));
[[1,0,0],[0,1,0],[0,0,1]]
@end example
Multivariate polynomials and rational functions may be expanded,
collected and normalized (i.e. converted to a ratio of two coprime
polynomials):
@example
> a = x^4 + 2*x^2*y^2 + 4*x^3*y + 12*x*y^3 - 3*y^4;
12*x*y^3+2*x^2*y^2+4*x^3*y-3*y^4+x^4
> b = x^2 + 4*x*y - y^2;
4*x*y-y^2+x^2
> expand(a*b);
8*x^5*y+17*x^4*y^2+43*x^2*y^4-24*x*y^5+16*x^3*y^3+3*y^6+x^6
> collect(a+b,x);
4*x^3*y-y^2-3*y^4+(12*y^3+4*y)*x+x^4+x^2*(1+2*y^2)
> collect(a+b,y);
12*x*y^3-3*y^4+(-1+2*x^2)*y^2+(4*x+4*x^3)*y+x^2+x^4
> normal(a/b);
3*y^2+x^2
@end example
You can differentiate functions and expand them as Taylor or Laurent
series in a very natural syntax (the second argument of @code{series} is
a relation defining the evaluation point, the third specifies the
order):
@cindex Zeta function
@example
> diff(tan(x),x);
tan(x)^2+1
> series(sin(x),x==0,4);
x-1/6*x^3+Order(x^4)
> series(1/tan(x),x==0,4);
x^(-1)-1/3*x+Order(x^2)
> series(tgamma(x),x==0,3);
x^(-1)-Euler+(1/12*Pi^2+1/2*Euler^2)*x+
(-1/3*zeta(3)-1/12*Pi^2*Euler-1/6*Euler^3)*x^2+Order(x^3)
> evalf(%);
x^(-1)-0.5772156649015328606+(0.9890559953279725555)*x
-(0.90747907608088628905)*x^2+Order(x^3)
> series(tgamma(2*sin(x)-2),x==Pi/2,6);
-(x-1/2*Pi)^(-2)+(-1/12*Pi^2-1/2*Euler^2-1/240)*(x-1/2*Pi)^2
-Euler-1/12+Order((x-1/2*Pi)^3)
@end example
Here we have made use of the @command{ginsh}-command @code{%} to pop the
previously evaluated element from @command{ginsh}'s internal stack.
Often, functions don't have roots in closed form. Nevertheless, it's
quite easy to compute a solution numerically, to arbitrary precision:
@cindex fsolve
@example
> Digits=50:
> fsolve(cos(x)==x,x,0,2);
0.7390851332151606416553120876738734040134117589007574649658
> f=exp(sin(x))-x:
> X=fsolve(f,x,-10,10);
2.2191071489137460325957851882042901681753665565320678854155
> subs(f,x==X);
-6.372367644529809108115521591070847222364418220770475144296E-58
@end example
Notice how the final result above differs slightly from zero by about
@math{6*10^(-58)}. This is because with 50 decimal digits precision the
root cannot be represented more accurately than @code{X}. Such
inaccuracies are to be expected when computing with finite floating
point values.
If you ever wanted to convert units in C or C++ and found this is
cumbersome, here is the solution. Symbolic types can always be used as
tags for different types of objects. Converting from wrong units to the
metric system is now easy:
@example
> in=.0254*m;
0.0254*m
> lb=.45359237*kg;
0.45359237*kg
> 200*lb/in^2;
140613.91592783185568*kg*m^(-2)
@end example
@node Installation, Prerequisites, What it can do for you, Top
@c node-name, next, previous, up
@chapter Installation
@cindex CLN
GiNaC's installation follows the spirit of most GNU software. It is
easily installed on your system by three steps: configuration, build,
installation.
@menu
* Prerequisites:: Packages upon which GiNaC depends.
* Configuration:: How to configure GiNaC.
* Building GiNaC:: How to compile GiNaC.
* Installing GiNaC:: How to install GiNaC on your system.
@end menu
@node Prerequisites, Configuration, Installation, Installation
@c node-name, next, previous, up
@section Prerequisites
In order to install GiNaC on your system, some prerequisites need to be
met. First of all, you need to have a C++-compiler adhering to the
ANSI-standard @cite{ISO/IEC 14882:1998(E)}. We used GCC for development
so if you have a different compiler you are on your own. For the
configuration to succeed you need a Posix compliant shell installed in
@file{/bin/sh}, GNU @command{bash} is fine. The pkg-config utility is
required for the configuration, it can be downloaded from
@uref{http://pkg-config.freedesktop.org}.
Last but not least, the CLN library
is used extensively and needs to be installed on your system.
Please get it from @uref{ftp://ftpthep.physik.uni-mainz.de/pub/gnu/}
(it is covered by GPL) and install it prior to trying to install
GiNaC. The configure script checks if it can find it and if it cannot
it will refuse to continue.
@node Configuration, Building GiNaC, Prerequisites, Installation
@c node-name, next, previous, up
@section Configuration
@cindex configuration
@cindex Autoconf
To configure GiNaC means to prepare the source distribution for
building. It is done via a shell script called @command{configure} that
is shipped with the sources and was originally generated by GNU
Autoconf. Since a configure script generated by GNU Autoconf never
prompts, all customization must be done either via command line
parameters or environment variables. It accepts a list of parameters,
the complete set of which can be listed by calling it with the
@option{--help} option. The most important ones will be shortly
described in what follows:
@itemize @bullet
@item
@option{--disable-shared}: When given, this option switches off the
build of a shared library, i.e. a @file{.so} file. This may be convenient
when developing because it considerably speeds up compilation.
@item
@option{--prefix=@var{PREFIX}}: The directory where the compiled library
and headers are installed. It defaults to @file{/usr/local} which means
that the library is installed in the directory @file{/usr/local/lib},
the header files in @file{/usr/local/include/ginac} and the documentation
(like this one) into @file{/usr/local/share/doc/GiNaC}.
@item
@option{--libdir=@var{LIBDIR}}: Use this option in case you want to have
the library installed in some other directory than
@file{@var{PREFIX}/lib/}.
@item
@option{--includedir=@var{INCLUDEDIR}}: Use this option in case you want
to have the header files installed in some other directory than
@file{@var{PREFIX}/include/ginac/}. For instance, if you specify
@option{--includedir=/usr/include} you will end up with the header files
sitting in the directory @file{/usr/include/ginac/}. Note that the
subdirectory @file{ginac} is enforced by this process in order to
keep the header files separated from others. This avoids some
clashes and allows for an easier deinstallation of GiNaC. This ought
to be considered A Good Thing (tm).
@item
@option{--datadir=@var{DATADIR}}: This option may be given in case you
want to have the documentation installed in some other directory than
@file{@var{PREFIX}/share/doc/GiNaC/}.
@end itemize
In addition, you may specify some environment variables. @env{CXX}
holds the path and the name of the C++ compiler in case you want to
override the default in your path. (The @command{configure} script
searches your path for @command{c++}, @command{g++}, @command{gcc},
@command{CC}, @command{cxx} and @command{cc++} in that order.) It may
be very useful to define some compiler flags with the @env{CXXFLAGS}
environment variable, like optimization, debugging information and
warning levels. If omitted, it defaults to @option{-g
-O2}.@footnote{The @command{configure} script is itself generated from
the file @file{configure.ac}. It is only distributed in packaged
releases of GiNaC. If you got the naked sources, e.g. from git, you
must generate @command{configure} along with the various
@file{Makefile.in} by using the @command{autoreconf} utility. This will
require a fair amount of support from your local toolchain, though.}
The whole process is illustrated in the following two
examples. (Substitute @command{setenv @var{VARIABLE} @var{value}} for
@command{export @var{VARIABLE}=@var{value}} if the Berkeley C shell is
your login shell.)
Here is a simple configuration for a site-wide GiNaC library assuming
everything is in default paths:
@example
$ export CXXFLAGS="-Wall -O2"
$ ./configure
@end example
And here is a configuration for a private static GiNaC library with
several components sitting in custom places (site-wide GCC and private
CLN). The compiler is persuaded to be picky and full assertions and
debugging information are switched on:
@example
$ export CXX=/usr/local/gnu/bin/c++
$ export CPPFLAGS="$(CPPFLAGS) -I$(HOME)/include"
$ export CXXFLAGS="$(CXXFLAGS) -DDO_GINAC_ASSERT -ggdb -Wall -pedantic"
$ export LDFLAGS="$(LDFLAGS) -L$(HOME)/lib"
$ ./configure --disable-shared --prefix=$(HOME)
@end example
@node Building GiNaC, Installing GiNaC, Configuration, Installation
@c node-name, next, previous, up
@section Building GiNaC
@cindex building GiNaC
After proper configuration you should just build the whole
library by typing
@example
$ make
@end example
at the command prompt and go for a cup of coffee. The exact time it
takes to compile GiNaC depends not only on the speed of your machines
but also on other parameters, for instance what value for @env{CXXFLAGS}
you entered. Optimization may be very time-consuming.
Just to make sure GiNaC works properly you may run a collection of
regression tests by typing
@example
$ make check
@end example
This will compile some sample programs, run them and check the output
for correctness. The regression tests fall in three categories. First,
the so called @emph{exams} are performed, simple tests where some
predefined input is evaluated (like a pupils' exam). Second, the
@emph{checks} test the coherence of results among each other with
possible random input. Third, some @emph{timings} are performed, which
benchmark some predefined problems with different sizes and display the
CPU time used in seconds. Each individual test should return a message
@samp{passed}. This is mostly intended to be a QA-check if something
was broken during development, not a sanity check of your system. Some
of the tests in sections @emph{checks} and @emph{timings} may require
insane amounts of memory and CPU time. Feel free to kill them if your
machine catches fire. Another quite important intent is to allow people
to fiddle around with optimization.
By default, the only documentation that will be built is this tutorial
in @file{.info} format. To build the GiNaC tutorial and reference manual
in HTML, DVI, PostScript, or PDF formats, use one of
@example
$ make html
$ make dvi
$ make ps
$ make pdf
@end example
Generally, the top-level Makefile runs recursively to the
subdirectories. It is therefore safe to go into any subdirectory
(@code{doc/}, @code{ginsh/}, @dots{}) and simply type @code{make}
@var{target} there in case something went wrong.
@node Installing GiNaC, Basic concepts, Building GiNaC, Installation
@c node-name, next, previous, up
@section Installing GiNaC
@cindex installation
To install GiNaC on your system, simply type
@example
$ make install
@end example
As described in the section about configuration the files will be
installed in the following directories (the directories will be created
if they don't already exist):
@itemize @bullet
@item
@file{libginac.a} will go into @file{@var{PREFIX}/lib/} (or
@file{@var{LIBDIR}}) which defaults to @file{/usr/local/lib/}.
So will @file{libginac.so} unless the configure script was
given the option @option{--disable-shared}. The proper symlinks
will be established as well.
@item
All the header files will be installed into @file{@var{PREFIX}/include/ginac/}
(or @file{@var{INCLUDEDIR}/ginac/}, if specified).
@item
All documentation (info) will be stuffed into
@file{@var{PREFIX}/share/doc/GiNaC/} (or
@file{@var{DATADIR}/doc/GiNaC/}, if @var{DATADIR} was specified).
@end itemize
For the sake of completeness we will list some other useful make
targets: @command{make clean} deletes all files generated by
@command{make}, i.e. all the object files. In addition @command{make
distclean} removes all files generated by the configuration and
@command{make maintainer-clean} goes one step further and deletes files
that may require special tools to rebuild (like the @command{libtool}
for instance). Finally @command{make uninstall} removes the installed
library, header files and documentation@footnote{Uninstallation does not
work after you have called @command{make distclean} since the
@file{Makefile} is itself generated by the configuration from
@file{Makefile.in} and hence deleted by @command{make distclean}. There
are two obvious ways out of this dilemma. First, you can run the
configuration again with the same @var{PREFIX} thus creating a
@file{Makefile} with a working @samp{uninstall} target. Second, you can
do it by hand since you now know where all the files went during
installation.}.
@node Basic concepts, Expressions, Installing GiNaC, Top
@c node-name, next, previous, up
@chapter Basic concepts
This chapter will describe the different fundamental objects that can be
handled by GiNaC. But before doing so, it is worthwhile introducing you
to the more commonly used class of expressions, representing a flexible
meta-class for storing all mathematical objects.
@menu
* Expressions:: The fundamental GiNaC class.
* Automatic evaluation:: Evaluation and canonicalization.
* Error handling:: How the library reports errors.
* The class hierarchy:: Overview of GiNaC's classes.
* Symbols:: Symbolic objects.
* Numbers:: Numerical objects.
* Constants:: Pre-defined constants.
* Fundamental containers:: Sums, products and powers.
* Lists:: Lists of expressions.
* Mathematical functions:: Mathematical functions.
* Relations:: Equality, Inequality and all that.
* Integrals:: Symbolic integrals.
* Matrices:: Matrices.
* Indexed objects:: Handling indexed quantities.
* Non-commutative objects:: Algebras with non-commutative products.
* Hash maps:: A faster alternative to std::map<>.
@end menu
@node Expressions, Automatic evaluation, Basic concepts, Basic concepts
@c node-name, next, previous, up
@section Expressions
@cindex expression (class @code{ex})
@cindex @code{has()}
The most common class of objects a user deals with is the expression
@code{ex}, representing a mathematical object like a variable, number,
function, sum, product, etc@dots{} Expressions may be put together to form
new expressions, passed as arguments to functions, and so on. Here is a
little collection of valid expressions:
@example
ex MyEx1 = 5; // simple number
ex MyEx2 = x + 2*y; // polynomial in x and y
ex MyEx3 = (x + 1)/(x - 1); // rational expression
ex MyEx4 = sin(x + 2*y) + 3*z + 41; // containing a function
ex MyEx5 = MyEx4 + 1; // similar to above
@end example
Expressions are handles to other more fundamental objects, that often
contain other expressions thus creating a tree of expressions
(@xref{Internal structures}, for particular examples). Most methods on
@code{ex} therefore run top-down through such an expression tree. For
example, the method @code{has()} scans recursively for occurrences of
something inside an expression. Thus, if you have declared @code{MyEx4}
as in the example above @code{MyEx4.has(y)} will find @code{y} inside
the argument of @code{sin} and hence return @code{true}.
The next sections will outline the general picture of GiNaC's class
hierarchy and describe the classes of objects that are handled by
@code{ex}.
@subsection Note: Expressions and STL containers
GiNaC expressions (@code{ex} objects) have value semantics (they can be
assigned, reassigned and copied like integral types) but the operator
@code{<} doesn't provide a well-defined ordering on them. In STL-speak,
expressions are @samp{Assignable} but not @samp{LessThanComparable}.
This implies that in order to use expressions in sorted containers such as
@code{std::map<>} and @code{std::set<>} you have to supply a suitable
comparison predicate. GiNaC provides such a predicate, called
@code{ex_is_less}. For example, a set of expressions should be defined
as @code{std::set<ex, ex_is_less>}.
Unsorted containers such as @code{std::vector<>} and @code{std::list<>}
don't pose a problem. A @code{std::vector<ex>} works as expected.
@xref{Information about expressions}, for more about comparing and ordering
expressions.
@node Automatic evaluation, Error handling, Expressions, Basic concepts
@c node-name, next, previous, up
@section Automatic evaluation and canonicalization of expressions
@cindex evaluation
GiNaC performs some automatic transformations on expressions, to simplify
them and put them into a canonical form. Some examples:
@example
ex MyEx1 = 2*x - 1 + x; // 3*x-1
ex MyEx2 = x - x; // 0
ex MyEx3 = cos(2*Pi); // 1
ex MyEx4 = x*y/x; // y
@end example
This behavior is usually referred to as @dfn{automatic} or @dfn{anonymous
evaluation}. GiNaC only performs transformations that are
@itemize @bullet
@item
at most of complexity
@tex
$O(n\log n)$
@end tex
@ifnottex
@math{O(n log n)}
@end ifnottex
@item
algebraically correct, possibly except for a set of measure zero (e.g.
@math{x/x} is transformed to @math{1} although this is incorrect for @math{x=0})
@end itemize
There are two types of automatic transformations in GiNaC that may not
behave in an entirely obvious way at first glance:
@itemize
@item
The terms of sums and products (and some other things like the arguments of
symmetric functions, the indices of symmetric tensors etc.) are re-ordered
into a canonical form that is deterministic, but not lexicographical or in
any other way easy to guess (it almost always depends on the number and
order of the symbols you define). However, constructing the same expression
twice, either implicitly or explicitly, will always result in the same
canonical form.
@item
Expressions of the form 'number times sum' are automatically expanded (this
has to do with GiNaC's internal representation of sums and products). For
example
@example
ex MyEx5 = 2*(x + y); // 2*x+2*y
ex MyEx6 = z*(x + y); // z*(x+y)
@end example
@end itemize
The general rule is that when you construct expressions, GiNaC automatically
creates them in canonical form, which might differ from the form you typed in
your program. This may create some awkward looking output (@samp{-y+x} instead
of @samp{x-y}) but allows for more efficient operation and usually yields
some immediate simplifications.
@cindex @code{eval()}
Internally, the anonymous evaluator in GiNaC is implemented by the methods
@example
ex ex::eval(int level = 0) const;
ex basic::eval(int level = 0) const;
@end example
but unless you are extending GiNaC with your own classes or functions, there
should never be any reason to call them explicitly. All GiNaC methods that
transform expressions, like @code{subs()} or @code{normal()}, automatically
re-evaluate their results.
@node Error handling, The class hierarchy, Automatic evaluation, Basic concepts
@c node-name, next, previous, up
@section Error handling
@cindex exceptions
@cindex @code{pole_error} (class)
GiNaC reports run-time errors by throwing C++ exceptions. All exceptions
generated by GiNaC are subclassed from the standard @code{exception} class
defined in the @file{<stdexcept>} header. In addition to the predefined
@code{logic_error}, @code{domain_error}, @code{out_of_range},
@code{invalid_argument}, @code{runtime_error}, @code{range_error} and
@code{overflow_error} types, GiNaC also defines a @code{pole_error}
exception that gets thrown when trying to evaluate a mathematical function
at a singularity.
The @code{pole_error} class has a member function
@example
int pole_error::degree() const;
@end example
that returns the order of the singularity (or 0 when the pole is
logarithmic or the order is undefined).
When using GiNaC it is useful to arrange for exceptions to be caught in
the main program even if you don't want to do any special error handling.
Otherwise whenever an error occurs in GiNaC, it will be delegated to the
default exception handler of your C++ compiler's run-time system which
usually only aborts the program without giving any information what went
wrong.
Here is an example for a @code{main()} function that catches and prints
exceptions generated by GiNaC:
@example
#include <iostream>
#include <stdexcept>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
int main()
@{
try @{
...
// code using GiNaC
...
@} catch (exception &p) @{
cerr << p.what() << endl;
return 1;
@}
return 0;
@}
@end example
@node The class hierarchy, Symbols, Error handling, Basic concepts
@c node-name, next, previous, up
@section The class hierarchy
GiNaC's class hierarchy consists of several classes representing
mathematical objects, all of which (except for @code{ex} and some
helpers) are internally derived from one abstract base class called
@code{basic}. You do not have to deal with objects of class
@code{basic}, instead you'll be dealing with symbols, numbers,
containers of expressions and so on.
@cindex container
@cindex atom
To get an idea about what kinds of symbolic composites may be built we
have a look at the most important classes in the class hierarchy and
some of the relations among the classes:
@ifnotinfo
@image{classhierarchy}
@end ifnotinfo
@ifinfo
<PICTURE MISSING>
@end ifinfo
The abstract classes shown here (the ones without drop-shadow) are of no
interest for the user. They are used internally in order to avoid code
duplication if two or more classes derived from them share certain
features. An example is @code{expairseq}, a container for a sequence of
pairs each consisting of one expression and a number (@code{numeric}).
What @emph{is} visible to the user are the derived classes @code{add}
and @code{mul}, representing sums and products. @xref{Internal
structures}, where these two classes are described in more detail. The
following table shortly summarizes what kinds of mathematical objects
are stored in the different classes:
@cartouche
@multitable @columnfractions .22 .78
@item @code{symbol} @tab Algebraic symbols @math{a}, @math{x}, @math{y}@dots{}
@item @code{constant} @tab Constants like
@tex
$\pi$
@end tex
@ifnottex
@math{Pi}
@end ifnottex
@item @code{numeric} @tab All kinds of numbers, @math{42}, @math{7/3*I}, @math{3.14159}@dots{}
@item @code{add} @tab Sums like @math{x+y} or @math{a-(2*b)+3}
@item @code{mul} @tab Products like @math{x*y} or @math{2*a^2*(x+y+z)/b}
@item @code{ncmul} @tab Products of non-commutative objects
@item @code{power} @tab Exponentials such as @math{x^2}, @math{a^b},
@tex
$\sqrt{2}$
@end tex
@ifnottex
@code{sqrt(}@math{2}@code{)}
@end ifnottex
@dots{}
@item @code{pseries} @tab Power Series, e.g. @math{x-1/6*x^3+1/120*x^5+O(x^7)}
@item @code{function} @tab A symbolic function like
@tex
$\sin 2x$
@end tex
@ifnottex
@math{sin(2*x)}
@end ifnottex
@item @code{lst} @tab Lists of expressions @{@math{x}, @math{2*y}, @math{3+z}@}
@item @code{matrix} @tab @math{m}x@math{n} matrices of expressions
@item @code{relational} @tab A relation like the identity @math{x}@code{==}@math{y}
@item @code{indexed} @tab Indexed object like @math{A_ij}
@item @code{tensor} @tab Special tensor like the delta and metric tensors
@item @code{idx} @tab Index of an indexed object
@item @code{varidx} @tab Index with variance
@item @code{spinidx} @tab Index with variance and dot (used in Weyl-van-der-Waerden spinor formalism)
@item @code{wildcard} @tab Wildcard for pattern matching
@item @code{structure} @tab Template for user-defined classes
@end multitable
@end cartouche
@node Symbols, Numbers, The class hierarchy, Basic concepts
@c node-name, next, previous, up
@section Symbols
@cindex @code{symbol} (class)
@cindex hierarchy of classes
@cindex atom
Symbolic indeterminates, or @dfn{symbols} for short, are for symbolic
manipulation what atoms are for chemistry.
A typical symbol definition looks like this:
@example
symbol x("x");
@end example
This definition actually contains three very different things:
@itemize
@item a C++ variable named @code{x}
@item a @code{symbol} object stored in this C++ variable; this object
represents the symbol in a GiNaC expression
@item the string @code{"x"} which is the name of the symbol, used (almost)
exclusively for printing expressions holding the symbol
@end itemize
Symbols have an explicit name, supplied as a string during construction,
because in C++, variable names can't be used as values, and the C++ compiler
throws them away during compilation.
It is possible to omit the symbol name in the definition:
@example
symbol x;
@end example
In this case, GiNaC will assign the symbol an internal, unique name of the
form @code{symbolNNN}. This won't affect the usability of the symbol but
the output of your calculations will become more readable if you give your
symbols sensible names (for intermediate expressions that are only used
internally such anonymous symbols can be quite useful, however).
Now, here is one important property of GiNaC that differentiates it from
other computer algebra programs you may have used: GiNaC does @emph{not} use
the names of symbols to tell them apart, but a (hidden) serial number that
is unique for each newly created @code{symbol} object. If you want to use
one and the same symbol in different places in your program, you must only
create one @code{symbol} object and pass that around. If you create another
symbol, even if it has the same name, GiNaC will treat it as a different
indeterminate.
Observe:
@example
ex f(int n)
@{
symbol x("x");
return pow(x, n);
@}
int main()
@{
symbol x("x");
ex e = f(6);
cout << e << endl;
// prints "x^6" which looks right, but...
cout << e.degree(x) << endl;
// ...this doesn't work. The symbol "x" here is different from the one
// in f() and in the expression returned by f(). Consequently, it
// prints "0".
@}
@end example
One possibility to ensure that @code{f()} and @code{main()} use the same
symbol is to pass the symbol as an argument to @code{f()}:
@example
ex f(int n, const ex & x)
@{
return pow(x, n);
@}
int main()
@{
symbol x("x");
// Now, f() uses the same symbol.
ex e = f(6, x);
cout << e.degree(x) << endl;
// prints "6", as expected
@}
@end example
Another possibility would be to define a global symbol @code{x} that is used
by both @code{f()} and @code{main()}. If you are using global symbols and
multiple compilation units you must take special care, however. Suppose
that you have a header file @file{globals.h} in your program that defines
a @code{symbol x("x");}. In this case, every unit that includes
@file{globals.h} would also get its own definition of @code{x} (because
header files are just inlined into the source code by the C++ preprocessor),
and hence you would again end up with multiple equally-named, but different,
symbols. Instead, the @file{globals.h} header should only contain a
@emph{declaration} like @code{extern symbol x;}, with the definition of
@code{x} moved into a C++ source file such as @file{globals.cpp}.
A different approach to ensuring that symbols used in different parts of
your program are identical is to create them with a @emph{factory} function
like this one:
@example
const symbol & get_symbol(const string & s)
@{
static map<string, symbol> directory;
map<string, symbol>::iterator i = directory.find(s);
if (i != directory.end())
return i->second;
else
return directory.insert(make_pair(s, symbol(s))).first->second;
@}
@end example
This function returns one newly constructed symbol for each name that is
passed in, and it returns the same symbol when called multiple times with
the same name. Using this symbol factory, we can rewrite our example like
this:
@example
ex f(int n)
@{
return pow(get_symbol("x"), n);
@}
int main()
@{
ex e = f(6);
// Both calls of get_symbol("x") yield the same symbol.
cout << e.degree(get_symbol("x")) << endl;
// prints "6"
@}
@end example
Instead of creating symbols from strings we could also have
@code{get_symbol()} take, for example, an integer number as its argument.
In this case, we would probably want to give the generated symbols names
that include this number, which can be accomplished with the help of an
@code{ostringstream}.
In general, if you're getting weird results from GiNaC such as an expression
@samp{x-x} that is not simplified to zero, you should check your symbol
definitions.
As we said, the names of symbols primarily serve for purposes of expression
output. But there are actually two instances where GiNaC uses the names for
identifying symbols: When constructing an expression from a string, and when
recreating an expression from an archive (@pxref{Input/output}).
In addition to its name, a symbol may contain a special string that is used
in LaTeX output:
@example
symbol x("x", "\\Box");
@end example
This creates a symbol that is printed as "@code{x}" in normal output, but
as "@code{\Box}" in LaTeX code (@xref{Input/output}, for more
information about the different output formats of expressions in GiNaC).
GiNaC automatically creates proper LaTeX code for symbols having names of
greek letters (@samp{alpha}, @samp{mu}, etc.).
@cindex @code{subs()}
Symbols in GiNaC can't be assigned values. If you need to store results of
calculations and give them a name, use C++ variables of type @code{ex}.
If you want to replace a symbol in an expression with something else, you
can invoke the expression's @code{.subs()} method
(@pxref{Substituting expressions}).
@cindex @code{realsymbol()}
By default, symbols are expected to stand in for complex values, i.e. they live
in the complex domain. As a consequence, operations like complex conjugation,
for example (@pxref{Complex expressions}), do @emph{not} evaluate if applied
to such symbols. Likewise @code{log(exp(x))} does not evaluate to @code{x},
because of the unknown imaginary part of @code{x}.
On the other hand, if you are sure that your symbols will hold only real
values, you would like to have such functions evaluated. Therefore GiNaC
allows you to specify
the domain of the symbol. Instead of @code{symbol x("x");} you can write
@code{realsymbol x("x");} to tell GiNaC that @code{x} stands in for real values.
@cindex @code{possymbol()}
Furthermore, it is also possible to declare a symbol as positive. This will,
for instance, enable the automatic simplification of @code{abs(x)} into
@code{x}. This is done by declaring the symbol as @code{possymbol x("x");}.
@node Numbers, Constants, Symbols, Basic concepts
@c node-name, next, previous, up
@section Numbers
@cindex @code{numeric} (class)
@cindex GMP
@cindex CLN
@cindex rational
@cindex fraction
For storing numerical things, GiNaC uses Bruno Haible's library CLN.
The classes therein serve as foundation classes for GiNaC. CLN stands
for Class Library for Numbers or alternatively for Common Lisp Numbers.
In order to find out more about CLN's internals, the reader is referred to
the documentation of that library. @inforef{Introduction, , cln}, for
more information. Suffice to say that it is by itself build on top of
another library, the GNU Multiple Precision library GMP, which is an
extremely fast library for arbitrary long integers and rationals as well
as arbitrary precision floating point numbers. It is very commonly used
by several popular cryptographic applications. CLN extends GMP by
several useful things: First, it introduces the complex number field
over either reals (i.e. floating point numbers with arbitrary precision)
or rationals. Second, it automatically converts rationals to integers
if the denominator is unity and complex numbers to real numbers if the
imaginary part vanishes and also correctly treats algebraic functions.
Third it provides good implementations of state-of-the-art algorithms
for all trigonometric and hyperbolic functions as well as for
calculation of some useful constants.
The user can construct an object of class @code{numeric} in several
ways. The following example shows the four most important constructors.
It uses construction from C-integer, construction of fractions from two
integers, construction from C-float and construction from a string:
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace GiNaC;
int main()
@{
numeric two = 2; // exact integer 2
numeric r(2,3); // exact fraction 2/3
numeric e(2.71828); // floating point number
numeric p = "3.14159265358979323846"; // constructor from string
// Trott's constant in scientific notation:
numeric trott("1.0841015122311136151E-2");
std::cout << two*p << std::endl; // floating point 6.283...
...
@end example
@cindex @code{I}
@cindex complex numbers
The imaginary unit in GiNaC is a predefined @code{numeric} object with the
name @code{I}:
@example
...
numeric z1 = 2-3*I; // exact complex number 2-3i
numeric z2 = 5.9+1.6*I; // complex floating point number
@}
@end example
It may be tempting to construct fractions by writing @code{numeric r(3/2)}.
This would, however, call C's built-in operator @code{/} for integers
first and result in a numeric holding a plain integer 1. @strong{Never
use the operator @code{/} on integers} unless you know exactly what you
are doing! Use the constructor from two integers instead, as shown in
the example above. Writing @code{numeric(1)/2} may look funny but works
also.
@cindex @code{Digits}
@cindex accuracy
We have seen now the distinction between exact numbers and floating
point numbers. Clearly, the user should never have to worry about
dynamically created exact numbers, since their `exactness' always
determines how they ought to be handled, i.e. how `long' they are. The
situation is different for floating point numbers. Their accuracy is
controlled by one @emph{global} variable, called @code{Digits}. (For
those readers who know about Maple: it behaves very much like Maple's
@code{Digits}). All objects of class numeric that are constructed from
then on will be stored with a precision matching that number of decimal
digits:
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
void foo()
@{
numeric three(3.0), one(1.0);
numeric x = one/three;
cout << "in " << Digits << " digits:" << endl;
cout << x << endl;
cout << Pi.evalf() << endl;
@}
int main()
@{
foo();
Digits = 60;
foo();
return 0;
@}
@end example
The above example prints the following output to screen:
@example
in 17 digits:
0.33333333333333333334
3.1415926535897932385
in 60 digits:
0.33333333333333333333333333333333333333333333333333333333333333333334
3.1415926535897932384626433832795028841971693993751058209749445923078
@end example
@cindex rounding
Note that the last number is not necessarily rounded as you would
naively expect it to be rounded in the decimal system. But note also,
that in both cases you got a couple of extra digits. This is because
numbers are internally stored by CLN as chunks of binary digits in order
to match your machine's word size and to not waste precision. Thus, on
architectures with different word size, the above output might even
differ with regard to actually computed digits.
It should be clear that objects of class @code{numeric} should be used
for constructing numbers or for doing arithmetic with them. The objects
one deals with most of the time are the polymorphic expressions @code{ex}.
@subsection Tests on numbers
Once you have declared some numbers, assigned them to expressions and
done some arithmetic with them it is frequently desired to retrieve some
kind of information from them like asking whether that number is
integer, rational, real or complex. For those cases GiNaC provides
several useful methods. (Internally, they fall back to invocations of
certain CLN functions.)
As an example, let's construct some rational number, multiply it with
some multiple of its denominator and test what comes out:
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
// some very important constants:
const numeric twentyone(21);
const numeric ten(10);
const numeric five(5);
int main()
@{
numeric answer = twentyone;
answer /= five;
cout << answer.is_integer() << endl; // false, it's 21/5
answer *= ten;
cout << answer.is_integer() << endl; // true, it's 42 now!
@}
@end example
Note that the variable @code{answer} is constructed here as an integer
by @code{numeric}'s copy constructor, but in an intermediate step it
holds a rational number represented as integer numerator and integer
denominator. When multiplied by 10, the denominator becomes unity and
the result is automatically converted to a pure integer again.
Internally, the underlying CLN is responsible for this behavior and we
refer the reader to CLN's documentation. Suffice to say that
the same behavior applies to complex numbers as well as return values of
certain functions. Complex numbers are automatically converted to real
numbers if the imaginary part becomes zero. The full set of tests that
can be applied is listed in the following table.
@cartouche
@multitable @columnfractions .30 .70
@item @strong{Method} @tab @strong{Returns true if the object is@dots{}}
@item @code{.is_zero()}
@tab @dots{}equal to zero
@item @code{.is_positive()}
@tab @dots{}not complex and greater than 0
@item @code{.is_negative()}
@tab @dots{}not complex and smaller than 0
@item @code{.is_integer()}
@tab @dots{}a (non-complex) integer
@item @code{.is_pos_integer()}
@tab @dots{}an integer and greater than 0
@item @code{.is_nonneg_integer()}
@tab @dots{}an integer and greater equal 0
@item @code{.is_even()}
@tab @dots{}an even integer
@item @code{.is_odd()}
@tab @dots{}an odd integer
@item @code{.is_prime()}
@tab @dots{}a prime integer (probabilistic primality test)
@item @code{.is_rational()}
@tab @dots{}an exact rational number (integers are rational, too)
@item @code{.is_real()}
@tab @dots{}a real integer, rational or float (i.e. is not complex)
@item @code{.is_cinteger()}
@tab @dots{}a (complex) integer (such as @math{2-3*I})
@item @code{.is_crational()}
@tab @dots{}an exact (complex) rational number (such as @math{2/3+7/2*I})
@end multitable
@end cartouche
@page
@subsection Numeric functions
The following functions can be applied to @code{numeric} objects and will be
evaluated immediately:
@cartouche
@multitable @columnfractions .30 .70
@item @strong{Name} @tab @strong{Function}
@item @code{inverse(z)}
@tab returns @math{1/z}
@cindex @code{inverse()} (numeric)
@item @code{pow(a, b)}
@tab exponentiation @math{a^b}
@item @code{abs(z)}
@tab absolute value
@item @code{real(z)}
@tab real part
@cindex @code{real()}
@item @code{imag(z)}
@tab imaginary part
@cindex @code{imag()}
@item @code{csgn(z)}
@tab complex sign (returns an @code{int})
@item @code{step(x)}
@tab step function (returns an @code{numeric})
@item @code{numer(z)}
@tab numerator of rational or complex rational number
@item @code{denom(z)}
@tab denominator of rational or complex rational number
@item @code{sqrt(z)}
@tab square root
@item @code{isqrt(n)}
@tab integer square root
@cindex @code{isqrt()}
@item @code{sin(z)}
@tab sine
@item @code{cos(z)}
@tab cosine
@item @code{tan(z)}
@tab tangent
@item @code{asin(z)}
@tab inverse sine
@item @code{acos(z)}
@tab inverse cosine
@item @code{atan(z)}
@tab inverse tangent
@item @code{atan(y, x)}
@tab inverse tangent with two arguments
@item @code{sinh(z)}
@tab hyperbolic sine
@item @code{cosh(z)}
@tab hyperbolic cosine
@item @code{tanh(z)}
@tab hyperbolic tangent
@item @code{asinh(z)}
@tab inverse hyperbolic sine
@item @code{acosh(z)}
@tab inverse hyperbolic cosine
@item @code{atanh(z)}
@tab inverse hyperbolic tangent
@item @code{exp(z)}
@tab exponential function
@item @code{log(z)}
@tab natural logarithm
@item @code{Li2(z)}
@tab dilogarithm
@item @code{zeta(z)}
@tab Riemann's zeta function
@item @code{tgamma(z)}
@tab gamma function
@item @code{lgamma(z)}
@tab logarithm of gamma function
@item @code{psi(z)}
@tab psi (digamma) function
@item @code{psi(n, z)}
@tab derivatives of psi function (polygamma functions)
@item @code{factorial(n)}
@tab factorial function @math{n!}
@item @code{doublefactorial(n)}
@tab double factorial function @math{n!!}
@cindex @code{doublefactorial()}
@item @code{binomial(n, k)}
@tab binomial coefficients
@item @code{bernoulli(n)}
@tab Bernoulli numbers
@cindex @code{bernoulli()}
@item @code{fibonacci(n)}
@tab Fibonacci numbers
@cindex @code{fibonacci()}
@item @code{mod(a, b)}
@tab modulus in positive representation (in the range @code{[0, abs(b)-1]} with the sign of b, or zero)
@cindex @code{mod()}
@item @code{smod(a, b)}
@tab modulus in symmetric representation (in the range @code{[-iquo(abs(b), 2), iquo(abs(b), 2)]})
@cindex @code{smod()}
@item @code{irem(a, b)}
@tab integer remainder (has the sign of @math{a}, or is zero)
@cindex @code{irem()}
@item @code{irem(a, b, q)}
@tab integer remainder and quotient, @code{irem(a, b, q) == a-q*b}
@item @code{iquo(a, b)}
@tab integer quotient
@cindex @code{iquo()}
@item @code{iquo(a, b, r)}
@tab integer quotient and remainder, @code{r == a-iquo(a, b)*b}
@item @code{gcd(a, b)}
@tab greatest common divisor
@item @code{lcm(a, b)}
@tab least common multiple
@end multitable
@end cartouche
Most of these functions are also available as symbolic functions that can be
used in expressions (@pxref{Mathematical functions}) or, like @code{gcd()},
as polynomial algorithms.
@subsection Converting numbers
Sometimes it is desirable to convert a @code{numeric} object back to a
built-in arithmetic type (@code{int}, @code{double}, etc.). The @code{numeric}
class provides a couple of methods for this purpose:
@cindex @code{to_int()}
@cindex @code{to_long()}
@cindex @code{to_double()}
@cindex @code{to_cl_N()}
@example
int numeric::to_int() const;
long numeric::to_long() const;
double numeric::to_double() const;
cln::cl_N numeric::to_cl_N() const;
@end example
@code{to_int()} and @code{to_long()} only work when the number they are
applied on is an exact integer. Otherwise the program will halt with a
message like @samp{Not a 32-bit integer}. @code{to_double()} applied on a
rational number will return a floating-point approximation. Both
@code{to_int()/to_long()} and @code{to_double()} discard the imaginary
part of complex numbers.
@node Constants, Fundamental containers, Numbers, Basic concepts
@c node-name, next, previous, up
@section Constants
@cindex @code{constant} (class)
@cindex @code{Pi}
@cindex @code{Catalan}
@cindex @code{Euler}
@cindex @code{evalf()}
Constants behave pretty much like symbols except that they return some
specific number when the method @code{.evalf()} is called.
The predefined known constants are:
@cartouche
@multitable @columnfractions .14 .32 .54
@item @strong{Name} @tab @strong{Common Name} @tab @strong{Numerical Value (to 35 digits)}
@item @code{Pi}
@tab Archimedes' constant
@tab 3.14159265358979323846264338327950288
@item @code{Catalan}
@tab Catalan's constant
@tab 0.91596559417721901505460351493238411
@item @code{Euler}
@tab Euler's (or Euler-Mascheroni) constant
@tab 0.57721566490153286060651209008240243
@end multitable
@end cartouche
@node Fundamental containers, Lists, Constants, Basic concepts
@c node-name, next, previous, up
@section Sums, products and powers
@cindex polynomial
@cindex @code{add}
@cindex @code{mul}
@cindex @code{power}
Simple rational expressions are written down in GiNaC pretty much like
in other CAS or like expressions involving numerical variables in C.
The necessary operators @code{+}, @code{-}, @code{*} and @code{/} have
been overloaded to achieve this goal. When you run the following
code snippet, the constructor for an object of type @code{mul} is
automatically called to hold the product of @code{a} and @code{b} and
then the constructor for an object of type @code{add} is called to hold
the sum of that @code{mul} object and the number one:
@example
...
symbol a("a"), b("b");
ex MyTerm = 1+a*b;
...
@end example
@cindex @code{pow()}
For exponentiation, you have already seen the somewhat clumsy (though C-ish)
statement @code{pow(x,2);} to represent @code{x} squared. This direct
construction is necessary since we cannot safely overload the constructor
@code{^} in C++ to construct a @code{power} object. If we did, it would
have several counterintuitive and undesired effects:
@itemize @bullet
@item
Due to C's operator precedence, @code{2*x^2} would be parsed as @code{(2*x)^2}.
@item
Due to the binding of the operator @code{^}, @code{x^a^b} would result in
@code{(x^a)^b}. This would be confusing since most (though not all) other CAS
interpret this as @code{x^(a^b)}.
@item
Also, expressions involving integer exponents are very frequently used,
which makes it even more dangerous to overload @code{^} since it is then
hard to distinguish between the semantics as exponentiation and the one
for exclusive or. (It would be embarrassing to return @code{1} where one
has requested @code{2^3}.)
@end itemize
@cindex @command{ginsh}
All effects are contrary to mathematical notation and differ from the
way most other CAS handle exponentiation, therefore overloading @code{^}
is ruled out for GiNaC's C++ part. The situation is different in
@command{ginsh}, there the exponentiation-@code{^} exists. (Also note
that the other frequently used exponentiation operator @code{**} does
not exist at all in C++).
To be somewhat more precise, objects of the three classes described
here, are all containers for other expressions. An object of class
@code{power} is best viewed as a container with two slots, one for the
basis, one for the exponent. All valid GiNaC expressions can be
inserted. However, basic transformations like simplifying
@code{pow(pow(x,2),3)} to @code{x^6} automatically are only performed
when this is mathematically possible. If we replace the outer exponent
three in the example by some symbols @code{a}, the simplification is not
safe and will not be performed, since @code{a} might be @code{1/2} and
@code{x} negative.
Objects of type @code{add} and @code{mul} are containers with an
arbitrary number of slots for expressions to be inserted. Again, simple
and safe simplifications are carried out like transforming
@code{3*x+4-x} to @code{2*x+4}.
@node Lists, Mathematical functions, Fundamental containers, Basic concepts
@c node-name, next, previous, up
@section Lists of expressions
@cindex @code{lst} (class)
@cindex lists
@cindex @code{nops()}
@cindex @code{op()}
@cindex @code{append()}
@cindex @code{prepend()}
@cindex @code{remove_first()}
@cindex @code{remove_last()}
@cindex @code{remove_all()}
The GiNaC class @code{lst} serves for holding a @dfn{list} of arbitrary
expressions. They are not as ubiquitous as in many other computer algebra
packages, but are sometimes used to supply a variable number of arguments of
the same type to GiNaC methods such as @code{subs()} and some @code{matrix}
constructors, so you should have a basic understanding of them.
Lists can be constructed by assigning a comma-separated sequence of
expressions:
@example
@{
symbol x("x"), y("y");
lst l;
l = x, 2, y, x+y;
// now, l is a list holding the expressions 'x', '2', 'y', and 'x+y',
// in that order
...
@end example
There are also constructors that allow direct creation of lists of up to
16 expressions, which is often more convenient but slightly less efficient:
@example
...
// This produces the same list 'l' as above:
// lst l(x, 2, y, x+y);
// lst l = lst(x, 2, y, x+y);
...
@end example
Use the @code{nops()} method to determine the size (number of expressions) of
a list and the @code{op()} method or the @code{[]} operator to access
individual elements:
@example
...
cout << l.nops() << endl; // prints '4'
cout << l.op(2) << " " << l[0] << endl; // prints 'y x'
...
@end example
As with the standard @code{list<T>} container, accessing random elements of a
@code{lst} is generally an operation of order @math{O(N)}. Faster read-only
sequential access to the elements of a list is possible with the
iterator types provided by the @code{lst} class:
@example
typedef ... lst::const_iterator;
typedef ... lst::const_reverse_iterator;
lst::const_iterator lst::begin() const;
lst::const_iterator lst::end() const;
lst::const_reverse_iterator lst::rbegin() const;
lst::const_reverse_iterator lst::rend() const;
@end example
For example, to print the elements of a list individually you can use:
@example
...
// O(N)
for (lst::const_iterator i = l.begin(); i != l.end(); ++i)
cout << *i << endl;
...
@end example
which is one order faster than
@example
...
// O(N^2)
for (size_t i = 0; i < l.nops(); ++i)
cout << l.op(i) << endl;
...
@end example
These iterators also allow you to use some of the algorithms provided by
the C++ standard library:
@example
...
// print the elements of the list (requires #include <iterator>)
std::copy(l.begin(), l.end(), ostream_iterator<ex>(cout, "\n"));
// sum up the elements of the list (requires #include <numeric>)
ex sum = std::accumulate(l.begin(), l.end(), ex(0));
cout << sum << endl; // prints '2+2*x+2*y'
...
@end example
@code{lst} is one of the few GiNaC classes that allow in-place modifications
(the only other one is @code{matrix}). You can modify single elements:
@example
...
l[1] = 42; // l is now @{x, 42, y, x+y@}
l.let_op(1) = 7; // l is now @{x, 7, y, x+y@}
...
@end example
You can append or prepend an expression to a list with the @code{append()}
and @code{prepend()} methods:
@example
...
l.append(4*x); // l is now @{x, 7, y, x+y, 4*x@}
l.prepend(0); // l is now @{0, x, 7, y, x+y, 4*x@}
...
@end example
You can remove the first or last element of a list with @code{remove_first()}
and @code{remove_last()}:
@example
...
l.remove_first(); // l is now @{x, 7, y, x+y, 4*x@}
l.remove_last(); // l is now @{x, 7, y, x+y@}
...
@end example
You can remove all the elements of a list with @code{remove_all()}:
@example
...
l.remove_all(); // l is now empty
...
@end example
You can bring the elements of a list into a canonical order with @code{sort()}:
@example
...
lst l1, l2;
l1 = x, 2, y, x+y;
l2 = 2, x+y, x, y;
l1.sort();
l2.sort();
// l1 and l2 are now equal
...
@end example
Finally, you can remove all but the first element of consecutive groups of
elements with @code{unique()}:
@example
...
lst l3;
l3 = x, 2, 2, 2, y, x+y, y+x;
l3.unique(); // l3 is now @{x, 2, y, x+y@}
@}
@end example
@node Mathematical functions, Relations, Lists, Basic concepts
@c node-name, next, previous, up
@section Mathematical functions
@cindex @code{function} (class)
@cindex trigonometric function
@cindex hyperbolic function
There are quite a number of useful functions hard-wired into GiNaC. For
instance, all trigonometric and hyperbolic functions are implemented
(@xref{Built-in functions}, for a complete list).
These functions (better called @emph{pseudofunctions}) are all objects
of class @code{function}. They accept one or more expressions as
arguments and return one expression. If the arguments are not
numerical, the evaluation of the function may be halted, as it does in
the next example, showing how a function returns itself twice and
finally an expression that may be really useful:
@cindex Gamma function
@cindex @code{subs()}
@example
...
symbol x("x"), y("y");
ex foo = x+y/2;
cout << tgamma(foo) << endl;
// -> tgamma(x+(1/2)*y)
ex bar = foo.subs(y==1);
cout << tgamma(bar) << endl;
// -> tgamma(x+1/2)
ex foobar = bar.subs(x==7);
cout << tgamma(foobar) << endl;
// -> (135135/128)*Pi^(1/2)
...
@end example
Besides evaluation most of these functions allow differentiation, series
expansion and so on. Read the next chapter in order to learn more about
this.
It must be noted that these pseudofunctions are created by inline
functions, where the argument list is templated. This means that
whenever you call @code{GiNaC::sin(1)} it is equivalent to
@code{sin(ex(1))} and will therefore not result in a floating point
number. Unless of course the function prototype is explicitly
overridden -- which is the case for arguments of type @code{numeric}
(not wrapped inside an @code{ex}). Hence, in order to obtain a floating
point number of class @code{numeric} you should call
@code{sin(numeric(1))}. This is almost the same as calling
@code{sin(1).evalf()} except that the latter will return a numeric
wrapped inside an @code{ex}.
@node Relations, Integrals, Mathematical functions, Basic concepts
@c node-name, next, previous, up
@section Relations
@cindex @code{relational} (class)
Sometimes, a relation holding between two expressions must be stored
somehow. The class @code{relational} is a convenient container for such
purposes. A relation is by definition a container for two @code{ex} and
a relation between them that signals equality, inequality and so on.
They are created by simply using the C++ operators @code{==}, @code{!=},
@code{<}, @code{<=}, @code{>} and @code{>=} between two expressions.
@xref{Mathematical functions}, for examples where various applications
of the @code{.subs()} method show how objects of class relational are
used as arguments. There they provide an intuitive syntax for
substitutions. They are also used as arguments to the @code{ex::series}
method, where the left hand side of the relation specifies the variable
to expand in and the right hand side the expansion point. They can also
be used for creating systems of equations that are to be solved for
unknown variables. But the most common usage of objects of this class
is rather inconspicuous in statements of the form @code{if
(expand(pow(a+b,2))==a*a+2*a*b+b*b) @{...@}}. Here, an implicit
conversion from @code{relational} to @code{bool} takes place. Note,
however, that @code{==} here does not perform any simplifications, hence
@code{expand()} must be called explicitly.
@node Integrals, Matrices, Relations, Basic concepts
@c node-name, next, previous, up
@section Integrals
@cindex @code{integral} (class)
An object of class @dfn{integral} can be used to hold a symbolic integral.
If you want to symbolically represent the integral of @code{x*x} from 0 to
1, you would write this as
@example
integral(x, 0, 1, x*x)
@end example
The first argument is the integration variable. It should be noted that
GiNaC is not very good (yet?) at symbolically evaluating integrals. In
fact, it can only integrate polynomials. An expression containing integrals
can be evaluated symbolically by calling the
@example
.eval_integ()
@end example
method on it. Numerical evaluation is available by calling the
@example
.evalf()
@end example
method on an expression containing the integral. This will only evaluate
integrals into a number if @code{subs}ing the integration variable by a
number in the fourth argument of an integral and then @code{evalf}ing the
result always results in a number. Of course, also the boundaries of the
integration domain must @code{evalf} into numbers. It should be noted that
trying to @code{evalf} a function with discontinuities in the integration
domain is not recommended. The accuracy of the numeric evaluation of
integrals is determined by the static member variable
@example
ex integral::relative_integration_error
@end example
of the class @code{integral}. The default value of this is 10^-8.
The integration works by halving the interval of integration, until numeric
stability of the answer indicates that the requested accuracy has been
reached. The maximum depth of the halving can be set via the static member
variable
@example
int integral::max_integration_level
@end example
The default value is 15. If this depth is exceeded, @code{evalf} will simply
return the integral unevaluated. The function that performs the numerical
evaluation, is also available as
@example
ex adaptivesimpson(const ex & x, const ex & a, const ex & b, const ex & f,
const ex & error)
@end example
This function will throw an exception if the maximum depth is exceeded. The
last parameter of the function is optional and defaults to the
@code{relative_integration_error}. To make sure that we do not do too
much work if an expression contains the same integral multiple times,
a lookup table is used.
If you know that an expression holds an integral, you can get the
integration variable, the left boundary, right boundary and integrand by
respectively calling @code{.op(0)}, @code{.op(1)}, @code{.op(2)}, and
@code{.op(3)}. Differentiating integrals with respect to variables works
as expected. Note that it makes no sense to differentiate an integral
with respect to the integration variable.
@node Matrices, Indexed objects, Integrals, Basic concepts
@c node-name, next, previous, up
@section Matrices
@cindex @code{matrix} (class)
A @dfn{matrix} is a two-dimensional array of expressions. The elements of a
matrix with @math{m} rows and @math{n} columns are accessed with two
@code{unsigned} indices, the first one in the range 0@dots{}@math{m-1}, the
second one in the range 0@dots{}@math{n-1}.
There are a couple of ways to construct matrices, with or without preset
elements. The constructor
@example
matrix::matrix(unsigned r, unsigned c);
@end example
creates a matrix with @samp{r} rows and @samp{c} columns with all elements
set to zero.
The fastest way to create a matrix with preinitialized elements is to assign
a list of comma-separated expressions to an empty matrix (see below for an
example). But you can also specify the elements as a (flat) list with
@example
matrix::matrix(unsigned r, unsigned c, const lst & l);
@end example
The function
@cindex @code{lst_to_matrix()}
@example
ex lst_to_matrix(const lst & l);
@end example
constructs a matrix from a list of lists, each list representing a matrix row.
There is also a set of functions for creating some special types of
matrices:
@cindex @code{diag_matrix()}
@cindex @code{unit_matrix()}
@cindex @code{symbolic_matrix()}
@example
ex diag_matrix(const lst & l);
ex unit_matrix(unsigned x);
ex unit_matrix(unsigned r, unsigned c);
ex symbolic_matrix(unsigned r, unsigned c, const string & base_name);
ex symbolic_matrix(unsigned r, unsigned c, const string & base_name,
const string & tex_base_name);
@end example
@code{diag_matrix()} constructs a diagonal matrix given the list of diagonal
elements. @code{unit_matrix()} creates an @samp{x} by @samp{x} (or @samp{r}
by @samp{c}) unit matrix. And finally, @code{symbolic_matrix} constructs a
matrix filled with newly generated symbols made of the specified base name
and the position of each element in the matrix.
Matrices often arise by omitting elements of another matrix. For
instance, the submatrix @code{S} of a matrix @code{M} takes a
rectangular block from @code{M}. The reduced matrix @code{R} is defined
by removing one row and one column from a matrix @code{M}. (The
determinant of a reduced matrix is called a @emph{Minor} of @code{M} and
can be used for computing the inverse using Cramer's rule.)
@cindex @code{sub_matrix()}
@cindex @code{reduced_matrix()}
@example
ex sub_matrix(const matrix&m, unsigned r, unsigned nr, unsigned c, unsigned nc);
ex reduced_matrix(const matrix& m, unsigned r, unsigned c);
@end example
The function @code{sub_matrix()} takes a row offset @code{r} and a
column offset @code{c} and takes a block of @code{nr} rows and @code{nc}
columns. The function @code{reduced_matrix()} has two integer arguments
that specify which row and column to remove:
@example
@{
matrix m(3,3);
m = 11, 12, 13,
21, 22, 23,
31, 32, 33;
cout << reduced_matrix(m, 1, 1) << endl;
// -> [[11,13],[31,33]]
cout << sub_matrix(m, 1, 2, 1, 2) << endl;
// -> [[22,23],[32,33]]
@}
@end example
Matrix elements can be accessed and set using the parenthesis (function call)
operator:
@example
const ex & matrix::operator()(unsigned r, unsigned c) const;
ex & matrix::operator()(unsigned r, unsigned c);
@end example
It is also possible to access the matrix elements in a linear fashion with
the @code{op()} method. But C++-style subscripting with square brackets
@samp{[]} is not available.
Here are a couple of examples for constructing matrices:
@example
@{
symbol a("a"), b("b");
matrix M(2, 2);
M = a, 0,
0, b;
cout << M << endl;
// -> [[a,0],[0,b]]
matrix M2(2, 2);
M2(0, 0) = a;
M2(1, 1) = b;
cout << M2 << endl;
// -> [[a,0],[0,b]]
cout << matrix(2, 2, lst(a, 0, 0, b)) << endl;
// -> [[a,0],[0,b]]
cout << lst_to_matrix(lst(lst(a, 0), lst(0, b))) << endl;
// -> [[a,0],[0,b]]
cout << diag_matrix(lst(a, b)) << endl;
// -> [[a,0],[0,b]]
cout << unit_matrix(3) << endl;
// -> [[1,0,0],[0,1,0],[0,0,1]]
cout << symbolic_matrix(2, 3, "x") << endl;
// -> [[x00,x01,x02],[x10,x11,x12]]
@}
@end example
@cindex @code{is_zero_matrix()}
The method @code{matrix::is_zero_matrix()} returns @code{true} only if
all entries of the matrix are zeros. There is also method
@code{ex::is_zero_matrix()} which returns @code{true} only if the
expression is zero or a zero matrix.
@cindex @code{transpose()}
There are three ways to do arithmetic with matrices. The first (and most
direct one) is to use the methods provided by the @code{matrix} class:
@example
matrix matrix::add(const matrix & other) const;
matrix matrix::sub(const matrix & other) const;
matrix matrix::mul(const matrix & other) const;
matrix matrix::mul_scalar(const ex & other) const;
matrix matrix::pow(const ex & expn) const;
matrix matrix::transpose() const;
@end example
All of these methods return the result as a new matrix object. Here is an
example that calculates @math{A*B-2*C} for three matrices @math{A}, @math{B}
and @math{C}:
@example
@{
matrix A(2, 2), B(2, 2), C(2, 2);
A = 1, 2,
3, 4;
B = -1, 0,
2, 1;
C = 8, 4,
2, 1;
matrix result = A.mul(B).sub(C.mul_scalar(2));
cout << result << endl;
// -> [[-13,-6],[1,2]]
...
@}
@end example
@cindex @code{evalm()}
The second (and probably the most natural) way is to construct an expression
containing matrices with the usual arithmetic operators and @code{pow()}.
For efficiency reasons, expressions with sums, products and powers of
matrices are not automatically evaluated in GiNaC. You have to call the
method
@example
ex ex::evalm() const;
@end example
to obtain the result:
@example
@{
...
ex e = A*B - 2*C;
cout << e << endl;
// -> [[1,2],[3,4]]*[[-1,0],[2,1]]-2*[[8,4],[2,1]]
cout << e.evalm() << endl;
// -> [[-13,-6],[1,2]]
...
@}
@end example
The non-commutativity of the product @code{A*B} in this example is
automatically recognized by GiNaC. There is no need to use a special
operator here. @xref{Non-commutative objects}, for more information about
dealing with non-commutative expressions.
Finally, you can work with indexed matrices and call @code{simplify_indexed()}
to perform the arithmetic:
@example
@{
...
idx i(symbol("i"), 2), j(symbol("j"), 2), k(symbol("k"), 2);
e = indexed(A, i, k) * indexed(B, k, j) - 2 * indexed(C, i, j);
cout << e << endl;
// -> -2*[[8,4],[2,1]].i.j+[[-1,0],[2,1]].k.j*[[1,2],[3,4]].i.k
cout << e.simplify_indexed() << endl;
// -> [[-13,-6],[1,2]].i.j
@}
@end example
Using indices is most useful when working with rectangular matrices and
one-dimensional vectors because you don't have to worry about having to
transpose matrices before multiplying them. @xref{Indexed objects}, for
more information about using matrices with indices, and about indices in
general.
The @code{matrix} class provides a couple of additional methods for
computing determinants, traces, characteristic polynomials and ranks:
@cindex @code{determinant()}
@cindex @code{trace()}
@cindex @code{charpoly()}
@cindex @code{rank()}
@example
ex matrix::determinant(unsigned algo=determinant_algo::automatic) const;
ex matrix::trace() const;
ex matrix::charpoly(const ex & lambda) const;
unsigned matrix::rank() const;
@end example
The @samp{algo} argument of @code{determinant()} allows to select
between different algorithms for calculating the determinant. The
asymptotic speed (as parametrized by the matrix size) can greatly differ
between those algorithms, depending on the nature of the matrix'
entries. The possible values are defined in the @file{flags.h} header
file. By default, GiNaC uses a heuristic to automatically select an
algorithm that is likely (but not guaranteed) to give the result most
quickly.
@cindex @code{inverse()} (matrix)
@cindex @code{solve()}
Matrices may also be inverted using the @code{ex matrix::inverse()}
method and linear systems may be solved with:
@example
matrix matrix::solve(const matrix & vars, const matrix & rhs,
unsigned algo=solve_algo::automatic) const;
@end example
Assuming the matrix object this method is applied on is an @code{m}
times @code{n} matrix, then @code{vars} must be a @code{n} times
@code{p} matrix of symbolic indeterminates and @code{rhs} a @code{m}
times @code{p} matrix. The returned matrix then has dimension @code{n}
times @code{p} and in the case of an underdetermined system will still
contain some of the indeterminates from @code{vars}. If the system is
overdetermined, an exception is thrown.
@node Indexed objects, Non-commutative objects, Matrices, Basic concepts
@c node-name, next, previous, up
@section Indexed objects
GiNaC allows you to handle expressions containing general indexed objects in
arbitrary spaces. It is also able to canonicalize and simplify such
expressions and perform symbolic dummy index summations. There are a number
of predefined indexed objects provided, like delta and metric tensors.
There are few restrictions placed on indexed objects and their indices and
it is easy to construct nonsense expressions, but our intention is to
provide a general framework that allows you to implement algorithms with
indexed quantities, getting in the way as little as possible.
@cindex @code{idx} (class)
@cindex @code{indexed} (class)
@subsection Indexed quantities and their indices
Indexed expressions in GiNaC are constructed of two special types of objects,
@dfn{index objects} and @dfn{indexed objects}.
@itemize @bullet
@cindex contravariant
@cindex covariant
@cindex variance
@item Index objects are of class @code{idx} or a subclass. Every index has
a @dfn{value} and a @dfn{dimension} (which is the dimension of the space
the index lives in) which can both be arbitrary expressions but are usually
a number or a simple symbol. In addition, indices of class @code{varidx} have
a @dfn{variance} (they can be co- or contravariant), and indices of class
@code{spinidx} have a variance and can be @dfn{dotted} or @dfn{undotted}.
@item Indexed objects are of class @code{indexed} or a subclass. They
contain a @dfn{base expression} (which is the expression being indexed), and
one or more indices.
@end itemize
@strong{Please notice:} when printing expressions, covariant indices and indices
without variance are denoted @samp{.i} while contravariant indices are
denoted @samp{~i}. Dotted indices have a @samp{*} in front of the index
value. In the following, we are going to use that notation in the text so
instead of @math{A^i_jk} we will write @samp{A~i.j.k}. Index dimensions are
not visible in the output.
A simple example shall illustrate the concepts:
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
int main()
@{
symbol i_sym("i"), j_sym("j");
idx i(i_sym, 3), j(j_sym, 3);
symbol A("A");
cout << indexed(A, i, j) << endl;
// -> A.i.j
cout << index_dimensions << indexed(A, i, j) << endl;
// -> A.i[3].j[3]
cout << dflt; // reset cout to default output format (dimensions hidden)
...
@end example
The @code{idx} constructor takes two arguments, the index value and the
index dimension. First we define two index objects, @code{i} and @code{j},
both with the numeric dimension 3. The value of the index @code{i} is the
symbol @code{i_sym} (which prints as @samp{i}) and the value of the index
@code{j} is the symbol @code{j_sym} (which prints as @samp{j}). Next we
construct an expression containing one indexed object, @samp{A.i.j}. It has
the symbol @code{A} as its base expression and the two indices @code{i} and
@code{j}.
The dimensions of indices are normally not visible in the output, but one
can request them to be printed with the @code{index_dimensions} manipulator,
as shown above.
Note the difference between the indices @code{i} and @code{j} which are of
class @code{idx}, and the index values which are the symbols @code{i_sym}
and @code{j_sym}. The indices of indexed objects cannot directly be symbols
or numbers but must be index objects. For example, the following is not
correct and will raise an exception:
@example
symbol i("i"), j("j");
e = indexed(A, i, j); // ERROR: indices must be of type idx
@end example
You can have multiple indexed objects in an expression, index values can
be numeric, and index dimensions symbolic:
@example
...
symbol B("B"), dim("dim");
cout << 4 * indexed(A, i)
+ indexed(B, idx(j_sym, 4), idx(2, 3), idx(i_sym, dim)) << endl;
// -> B.j.2.i+4*A.i
...
@end example
@code{B} has a 4-dimensional symbolic index @samp{k}, a 3-dimensional numeric
index of value 2, and a symbolic index @samp{i} with the symbolic dimension
@samp{dim}. Note that GiNaC doesn't automatically notify you that the free
indices of @samp{A} and @samp{B} in the sum don't match (you have to call
@code{simplify_indexed()} for that, see below).
In fact, base expressions, index values and index dimensions can be
arbitrary expressions:
@example
...
cout << indexed(A+B, idx(2*i_sym+1, dim/2)) << endl;
// -> (B+A).(1+2*i)
...
@end example
It's also possible to construct nonsense like @samp{Pi.sin(x)}. You will not
get an error message from this but you will probably not be able to do
anything useful with it.
@cindex @code{get_value()}
@cindex @code{get_dim()}
The methods
@example
ex idx::get_value();
ex idx::get_dim();
@end example
return the value and dimension of an @code{idx} object. If you have an index
in an expression, such as returned by calling @code{.op()} on an indexed
object, you can get a reference to the @code{idx} object with the function
@code{ex_to<idx>()} on the expression.
There are also the methods
@example
bool idx::is_numeric();
bool idx::is_symbolic();
bool idx::is_dim_numeric();
bool idx::is_dim_symbolic();
@end example
for checking whether the value and dimension are numeric or symbolic
(non-numeric). Using the @code{info()} method of an index (see @ref{Information
about expressions}) returns information about the index value.
@cindex @code{varidx} (class)
If you need co- and contravariant indices, use the @code{varidx} class:
@example
...
symbol mu_sym("mu"), nu_sym("nu");
varidx mu(mu_sym, 4), nu(nu_sym, 4); // default is contravariant ~mu, ~nu
varidx mu_co(mu_sym, 4, true); // covariant index .mu
cout << indexed(A, mu, nu) << endl;
// -> A~mu~nu
cout << indexed(A, mu_co, nu) << endl;
// -> A.mu~nu
cout << indexed(A, mu.toggle_variance(), nu) << endl;
// -> A.mu~nu
...
@end example
A @code{varidx} is an @code{idx} with an additional flag that marks it as
co- or contravariant. The default is a contravariant (upper) index, but
this can be overridden by supplying a third argument to the @code{varidx}
constructor. The two methods
@example
bool varidx::is_covariant();
bool varidx::is_contravariant();
@end example
allow you to check the variance of a @code{varidx} object (use @code{ex_to<varidx>()}
to get the object reference from an expression). There's also the very useful
method
@example
ex varidx::toggle_variance();
@end example
which makes a new index with the same value and dimension but the opposite
variance. By using it you only have to define the index once.
@cindex @code{spinidx} (class)
The @code{spinidx} class provides dotted and undotted variant indices, as
used in the Weyl-van-der-Waerden spinor formalism:
@example
...
symbol K("K"), C_sym("C"), D_sym("D");
spinidx C(C_sym, 2), D(D_sym); // default is 2-dimensional,
// contravariant, undotted
spinidx C_co(C_sym, 2, true); // covariant index
spinidx D_dot(D_sym, 2, false, true); // contravariant, dotted
spinidx D_co_dot(D_sym, 2, true, true); // covariant, dotted
cout << indexed(K, C, D) << endl;
// -> K~C~D
cout << indexed(K, C_co, D_dot) << endl;
// -> K.C~*D
cout << indexed(K, D_co_dot, D) << endl;
// -> K.*D~D
...
@end example
A @code{spinidx} is a @code{varidx} with an additional flag that marks it as
dotted or undotted. The default is undotted but this can be overridden by
supplying a fourth argument to the @code{spinidx} constructor. The two
methods
@example
bool spinidx::is_dotted();
bool spinidx::is_undotted();
@end example
allow you to check whether or not a @code{spinidx} object is dotted (use
@code{ex_to<spinidx>()} to get the object reference from an expression).
Finally, the two methods
@example
ex spinidx::toggle_dot();
ex spinidx::toggle_variance_dot();
@end example
create a new index with the same value and dimension but opposite dottedness
and the same or opposite variance.
@subsection Substituting indices
@cindex @code{subs()}
Sometimes you will want to substitute one symbolic index with another
symbolic or numeric index, for example when calculating one specific element
of a tensor expression. This is done with the @code{.subs()} method, as it
is done for symbols (see @ref{Substituting expressions}).
You have two possibilities here. You can either substitute the whole index
by another index or expression:
@example
...
ex e = indexed(A, mu_co);
cout << e << " becomes " << e.subs(mu_co == nu) << endl;
// -> A.mu becomes A~nu
cout << e << " becomes " << e.subs(mu_co == varidx(0, 4)) << endl;
// -> A.mu becomes A~0
cout << e << " becomes " << e.subs(mu_co == 0) << endl;
// -> A.mu becomes A.0
...
@end example
The third example shows that trying to replace an index with something that
is not an index will substitute the index value instead.
Alternatively, you can substitute the @emph{symbol} of a symbolic index by
another expression:
@example
...
ex e = indexed(A, mu_co);
cout << e << " becomes " << e.subs(mu_sym == nu_sym) << endl;
// -> A.mu becomes A.nu
cout << e << " becomes " << e.subs(mu_sym == 0) << endl;
// -> A.mu becomes A.0
...
@end example
As you see, with the second method only the value of the index will get
substituted. Its other properties, including its dimension, remain unchanged.
If you want to change the dimension of an index you have to substitute the
whole index by another one with the new dimension.
Finally, substituting the base expression of an indexed object works as
expected:
@example
...
ex e = indexed(A, mu_co);
cout << e << " becomes " << e.subs(A == A+B) << endl;
// -> A.mu becomes (B+A).mu
...
@end example
@subsection Symmetries
@cindex @code{symmetry} (class)
@cindex @code{sy_none()}
@cindex @code{sy_symm()}
@cindex @code{sy_anti()}
@cindex @code{sy_cycl()}
Indexed objects can have certain symmetry properties with respect to their
indices. Symmetries are specified as a tree of objects of class @code{symmetry}
that is constructed with the helper functions
@example
symmetry sy_none(...);
symmetry sy_symm(...);
symmetry sy_anti(...);
symmetry sy_cycl(...);
@end example
@code{sy_none()} stands for no symmetry, @code{sy_symm()} and @code{sy_anti()}
specify fully symmetric or antisymmetric, respectively, and @code{sy_cycl()}
represents a cyclic symmetry. Each of these functions accepts up to four
arguments which can be either symmetry objects themselves or unsigned integer
numbers that represent an index position (counting from 0). A symmetry
specification that consists of only a single @code{sy_symm()}, @code{sy_anti()}
or @code{sy_cycl()} with no arguments specifies the respective symmetry for
all indices.
Here are some examples of symmetry definitions:
@example
...
// No symmetry:
e = indexed(A, i, j);
e = indexed(A, sy_none(), i, j); // equivalent
e = indexed(A, sy_none(0, 1), i, j); // equivalent
// Symmetric in all three indices:
e = indexed(A, sy_symm(), i, j, k);
e = indexed(A, sy_symm(0, 1, 2), i, j, k); // equivalent
e = indexed(A, sy_symm(2, 0, 1), i, j, k); // same symmetry, but yields a
// different canonical order
// Symmetric in the first two indices only:
e = indexed(A, sy_symm(0, 1), i, j, k);
e = indexed(A, sy_none(sy_symm(0, 1), 2), i, j, k); // equivalent
// Antisymmetric in the first and last index only (index ranges need not
// be contiguous):
e = indexed(A, sy_anti(0, 2), i, j, k);
e = indexed(A, sy_none(sy_anti(0, 2), 1), i, j, k); // equivalent
// An example of a mixed symmetry: antisymmetric in the first two and
// last two indices, symmetric when swapping the first and last index
// pairs (like the Riemann curvature tensor):
e = indexed(A, sy_symm(sy_anti(0, 1), sy_anti(2, 3)), i, j, k, l);
// Cyclic symmetry in all three indices:
e = indexed(A, sy_cycl(), i, j, k);
e = indexed(A, sy_cycl(0, 1, 2), i, j, k); // equivalent
// The following examples are invalid constructions that will throw
// an exception at run time.
// An index may not appear multiple times:
e = indexed(A, sy_symm(0, 0, 1), i, j, k); // ERROR
e = indexed(A, sy_none(sy_symm(0, 1), sy_anti(0, 2)), i, j, k); // ERROR
// Every child of sy_symm(), sy_anti() and sy_cycl() must refer to the
// same number of indices:
e = indexed(A, sy_symm(sy_anti(0, 1), 2), i, j, k); // ERROR
// And of course, you cannot specify indices which are not there:
e = indexed(A, sy_symm(0, 1, 2, 3), i, j, k); // ERROR
...
@end example
If you need to specify more than four indices, you have to use the
@code{.add()} method of the @code{symmetry} class. For example, to specify
full symmetry in the first six indices you would write
@code{sy_symm(0, 1, 2, 3).add(4).add(5)}.
If an indexed object has a symmetry, GiNaC will automatically bring the
indices into a canonical order which allows for some immediate simplifications:
@example
...
cout << indexed(A, sy_symm(), i, j)
+ indexed(A, sy_symm(), j, i) << endl;
// -> 2*A.j.i
cout << indexed(B, sy_anti(), i, j)
+ indexed(B, sy_anti(), j, i) << endl;
// -> 0
cout << indexed(B, sy_anti(), i, j, k)
- indexed(B, sy_anti(), j, k, i) << endl;
// -> 0
...
@end example
@cindex @code{get_free_indices()}
@cindex dummy index
@subsection Dummy indices
GiNaC treats certain symbolic index pairs as @dfn{dummy indices} meaning
that a summation over the index range is implied. Symbolic indices which are
not dummy indices are called @dfn{free indices}. Numeric indices are neither
dummy nor free indices.
To be recognized as a dummy index pair, the two indices must be of the same
class and their value must be the same single symbol (an index like
@samp{2*n+1} is never a dummy index). If the indices are of class
@code{varidx} they must also be of opposite variance; if they are of class
@code{spinidx} they must be both dotted or both undotted.
The method @code{.get_free_indices()} returns a vector containing the free
indices of an expression. It also checks that the free indices of the terms
of a sum are consistent:
@example
@{
symbol A("A"), B("B"), C("C");
symbol i_sym("i"), j_sym("j"), k_sym("k"), l_sym("l");
idx i(i_sym, 3), j(j_sym, 3), k(k_sym, 3), l(l_sym, 3);
ex e = indexed(A, i, j) * indexed(B, j, k) + indexed(C, k, l, i, l);
cout << exprseq(e.get_free_indices()) << endl;
// -> (.i,.k)
// 'j' and 'l' are dummy indices
symbol mu_sym("mu"), nu_sym("nu"), rho_sym("rho"), sigma_sym("sigma");
varidx mu(mu_sym, 4), nu(nu_sym, 4), rho(rho_sym, 4), sigma(sigma_sym, 4);
e = indexed(A, mu, nu) * indexed(B, nu.toggle_variance(), rho)
+ indexed(C, mu, sigma, rho, sigma.toggle_variance());
cout << exprseq(e.get_free_indices()) << endl;
// -> (~mu,~rho)
// 'nu' is a dummy index, but 'sigma' is not
e = indexed(A, mu, mu);
cout << exprseq(e.get_free_indices()) << endl;
// -> (~mu)
// 'mu' is not a dummy index because it appears twice with the same
// variance
e = indexed(A, mu, nu) + 42;
cout << exprseq(e.get_free_indices()) << endl; // ERROR
// this will throw an exception:
// "add::get_free_indices: inconsistent indices in sum"
@}
@end example
@cindex @code{expand_dummy_sum()}
A dummy index summation like
@tex
$ a_i b^i$
@end tex
@ifnottex
a.i b~i
@end ifnottex
can be expanded for indices with numeric
dimensions (e.g. 3) into the explicit sum like
@tex
$a_1b^1+a_2b^2+a_3b^3 $.
@end tex
@ifnottex
a.1 b~1 + a.2 b~2 + a.3 b~3.
@end ifnottex
This is performed by the function
@example
ex expand_dummy_sum(const ex & e, bool subs_idx = false);
@end example
which takes an expression @code{e} and returns the expanded sum for all
dummy indices with numeric dimensions. If the parameter @code{subs_idx}
is set to @code{true} then all substitutions are made by @code{idx} class
indices, i.e. without variance. In this case the above sum
@tex
$ a_i b^i$
@end tex
@ifnottex
a.i b~i
@end ifnottex
will be expanded to
@tex
$a_1b_1+a_2b_2+a_3b_3 $.
@end tex
@ifnottex
a.1 b.1 + a.2 b.2 + a.3 b.3.
@end ifnottex
@cindex @code{simplify_indexed()}
@subsection Simplifying indexed expressions
In addition to the few automatic simplifications that GiNaC performs on
indexed expressions (such as re-ordering the indices of symmetric tensors
and calculating traces and convolutions of matrices and predefined tensors)
there is the method
@example
ex ex::simplify_indexed();
ex ex::simplify_indexed(const scalar_products & sp);
@end example
that performs some more expensive operations:
@itemize @bullet
@item it checks the consistency of free indices in sums in the same way
@code{get_free_indices()} does
@item it tries to give dummy indices that appear in different terms of a sum
the same name to allow simplifications like @math{a_i*b_i-a_j*b_j=0}
@item it (symbolically) calculates all possible dummy index summations/contractions
with the predefined tensors (this will be explained in more detail in the
next section)
@item it detects contractions that vanish for symmetry reasons, for example
the contraction of a symmetric and a totally antisymmetric tensor
@item as a special case of dummy index summation, it can replace scalar products
of two tensors with a user-defined value
@end itemize
The last point is done with the help of the @code{scalar_products} class
which is used to store scalar products with known values (this is not an
arithmetic class, you just pass it to @code{simplify_indexed()}):
@example
@{
symbol A("A"), B("B"), C("C"), i_sym("i");
idx i(i_sym, 3);
scalar_products sp;
sp.add(A, B, 0); // A and B are orthogonal
sp.add(A, C, 0); // A and C are orthogonal
sp.add(A, A, 4); // A^2 = 4 (A has length 2)
e = indexed(A + B, i) * indexed(A + C, i);
cout << e << endl;
// -> (B+A).i*(A+C).i
cout << e.expand(expand_options::expand_indexed).simplify_indexed(sp)
<< endl;
// -> 4+C.i*B.i
@}
@end example
The @code{scalar_products} object @code{sp} acts as a storage for the
scalar products added to it with the @code{.add()} method. This method
takes three arguments: the two expressions of which the scalar product is
taken, and the expression to replace it with.
@cindex @code{expand()}
The example above also illustrates a feature of the @code{expand()} method:
if passed the @code{expand_indexed} option it will distribute indices
over sums, so @samp{(A+B).i} becomes @samp{A.i+B.i}.
@cindex @code{tensor} (class)
@subsection Predefined tensors
Some frequently used special tensors such as the delta, epsilon and metric
tensors are predefined in GiNaC. They have special properties when
contracted with other tensor expressions and some of them have constant
matrix representations (they will evaluate to a number when numeric
indices are specified).
@cindex @code{delta_tensor()}
@subsubsection Delta tensor
The delta tensor takes two indices, is symmetric and has the matrix
representation @code{diag(1, 1, 1, ...)}. It is constructed by the function
@code{delta_tensor()}:
@example
@{
symbol A("A"), B("B");
idx i(symbol("i"), 3), j(symbol("j"), 3),
k(symbol("k"), 3), l(symbol("l"), 3);
ex e = indexed(A, i, j) * indexed(B, k, l)
* delta_tensor(i, k) * delta_tensor(j, l);
cout << e.simplify_indexed() << endl;
// -> B.i.j*A.i.j
cout << delta_tensor(i, i) << endl;
// -> 3
@}
@end example
@cindex @code{metric_tensor()}
@subsubsection General metric tensor
The function @code{metric_tensor()} creates a general symmetric metric
tensor with two indices that can be used to raise/lower tensor indices. The
metric tensor is denoted as @samp{g} in the output and if its indices are of
mixed variance it is automatically replaced by a delta tensor:
@example
@{
symbol A("A");
varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4), rho(symbol("rho"), 4);
ex e = metric_tensor(mu, nu) * indexed(A, nu.toggle_variance(), rho);
cout << e.simplify_indexed() << endl;
// -> A~mu~rho
e = delta_tensor(mu, nu.toggle_variance()) * metric_tensor(nu, rho);
cout << e.simplify_indexed() << endl;
// -> g~mu~rho
e = metric_tensor(mu.toggle_variance(), nu.toggle_variance())
* metric_tensor(nu, rho);
cout << e.simplify_indexed() << endl;
// -> delta.mu~rho
e = metric_tensor(nu.toggle_variance(), rho.toggle_variance())
* metric_tensor(mu, nu) * (delta_tensor(mu.toggle_variance(), rho)
+ indexed(A, mu.toggle_variance(), rho));
cout << e.simplify_indexed() << endl;
// -> 4+A.rho~rho
@}
@end example
@cindex @code{lorentz_g()}
@subsubsection Minkowski metric tensor
The Minkowski metric tensor is a special metric tensor with a constant
matrix representation which is either @code{diag(1, -1, -1, ...)} (negative
signature, the default) or @code{diag(-1, 1, 1, ...)} (positive signature).
It is created with the function @code{lorentz_g()} (although it is output as
@samp{eta}):
@example
@{
varidx mu(symbol("mu"), 4);
e = delta_tensor(varidx(0, 4), mu.toggle_variance())
* lorentz_g(mu, varidx(0, 4)); // negative signature
cout << e.simplify_indexed() << endl;
// -> 1
e = delta_tensor(varidx(0, 4), mu.toggle_variance())
* lorentz_g(mu, varidx(0, 4), true); // positive signature
cout << e.simplify_indexed() << endl;
// -> -1
@}
@end example
@cindex @code{spinor_metric()}
@subsubsection Spinor metric tensor
The function @code{spinor_metric()} creates an antisymmetric tensor with
two indices that is used to raise/lower indices of 2-component spinors.
It is output as @samp{eps}:
@example
@{
symbol psi("psi");
spinidx A(symbol("A")), B(symbol("B")), C(symbol("C"));
ex A_co = A.toggle_variance(), B_co = B.toggle_variance();
e = spinor_metric(A, B) * indexed(psi, B_co);
cout << e.simplify_indexed() << endl;
// -> psi~A
e = spinor_metric(A, B) * indexed(psi, A_co);
cout << e.simplify_indexed() << endl;
// -> -psi~B
e = spinor_metric(A_co, B_co) * indexed(psi, B);
cout << e.simplify_indexed() << endl;
// -> -psi.A
e = spinor_metric(A_co, B_co) * indexed(psi, A);
cout << e.simplify_indexed() << endl;
// -> psi.B
e = spinor_metric(A_co, B_co) * spinor_metric(A, B);
cout << e.simplify_indexed() << endl;
// -> 2
e = spinor_metric(A_co, B_co) * spinor_metric(B, C);
cout << e.simplify_indexed() << endl;
// -> -delta.A~C
@}
@end example
The matrix representation of the spinor metric is @code{[[0, 1], [-1, 0]]}.
@cindex @code{epsilon_tensor()}
@cindex @code{lorentz_eps()}
@subsubsection Epsilon tensor
The epsilon tensor is totally antisymmetric, its number of indices is equal
to the dimension of the index space (the indices must all be of the same
numeric dimension), and @samp{eps.1.2.3...} (resp. @samp{eps~0~1~2...}) is
defined to be 1. Its behavior with indices that have a variance also
depends on the signature of the metric. Epsilon tensors are output as
@samp{eps}.
There are three functions defined to create epsilon tensors in 2, 3 and 4
dimensions:
@example
ex epsilon_tensor(const ex & i1, const ex & i2);
ex epsilon_tensor(const ex & i1, const ex & i2, const ex & i3);
ex lorentz_eps(const ex & i1, const ex & i2, const ex & i3, const ex & i4,
bool pos_sig = false);
@end example
The first two functions create an epsilon tensor in 2 or 3 Euclidean
dimensions, the last function creates an epsilon tensor in a 4-dimensional
Minkowski space (the last @code{bool} argument specifies whether the metric
has negative or positive signature, as in the case of the Minkowski metric
tensor):
@example
@{
varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4), rho(symbol("rho"), 4),
sig(symbol("sig"), 4), lam(symbol("lam"), 4), bet(symbol("bet"), 4);
e = lorentz_eps(mu, nu, rho, sig) *
lorentz_eps(mu.toggle_variance(), nu.toggle_variance(), lam, bet);
cout << simplify_indexed(e) << endl;
// -> 2*eta~bet~rho*eta~sig~lam-2*eta~sig~bet*eta~rho~lam
idx i(symbol("i"), 3), j(symbol("j"), 3), k(symbol("k"), 3);
symbol A("A"), B("B");
e = epsilon_tensor(i, j, k) * indexed(A, j) * indexed(B, k);
cout << simplify_indexed(e) << endl;
// -> -B.k*A.j*eps.i.k.j
e = epsilon_tensor(i, j, k) * indexed(A, j) * indexed(A, k);
cout << simplify_indexed(e) << endl;
// -> 0
@}
@end example
@subsection Linear algebra
The @code{matrix} class can be used with indices to do some simple linear
algebra (linear combinations and products of vectors and matrices, traces
and scalar products):
@example
@{
idx i(symbol("i"), 2), j(symbol("j"), 2);
symbol x("x"), y("y");
// A is a 2x2 matrix, X is a 2x1 vector
matrix A(2, 2), X(2, 1);
A = 1, 2,
3, 4;
X = x, y;
cout << indexed(A, i, i) << endl;
// -> 5
ex e = indexed(A, i, j) * indexed(X, j);
cout << e.simplify_indexed() << endl;
// -> [[2*y+x],[4*y+3*x]].i
e = indexed(A, i, j) * indexed(X, i) + indexed(X, j) * 2;
cout << e.simplify_indexed() << endl;
// -> [[3*y+3*x,6*y+2*x]].j
@}
@end example
You can of course obtain the same results with the @code{matrix::add()},
@code{matrix::mul()} and @code{matrix::trace()} methods (@pxref{Matrices})
but with indices you don't have to worry about transposing matrices.
Matrix indices always start at 0 and their dimension must match the number
of rows/columns of the matrix. Matrices with one row or one column are
vectors and can have one or two indices (it doesn't matter whether it's a
row or a column vector). Other matrices must have two indices.
You should be careful when using indices with variance on matrices. GiNaC
doesn't look at the variance and doesn't know that @samp{F~mu~nu} and
@samp{F.mu.nu} are different matrices. In this case you should use only
one form for @samp{F} and explicitly multiply it with a matrix representation
of the metric tensor.
@node Non-commutative objects, Hash maps, Indexed objects, Basic concepts
@c node-name, next, previous, up
@section Non-commutative objects
GiNaC is equipped to handle certain non-commutative algebras. Three classes of
non-commutative objects are built-in which are mostly of use in high energy
physics:
@itemize
@item Clifford (Dirac) algebra (class @code{clifford})
@item su(3) Lie algebra (class @code{color})
@item Matrices (unindexed) (class @code{matrix})
@end itemize
The @code{clifford} and @code{color} classes are subclasses of
@code{indexed} because the elements of these algebras usually carry
indices. The @code{matrix} class is described in more detail in
@ref{Matrices}.
Unlike most computer algebra systems, GiNaC does not primarily provide an
operator (often denoted @samp{&*}) for representing inert products of
arbitrary objects. Rather, non-commutativity in GiNaC is a property of the
classes of objects involved, and non-commutative products are formed with
the usual @samp{*} operator, as are ordinary products. GiNaC is capable of
figuring out by itself which objects commutate and will group the factors
by their class. Consider this example:
@example
...
varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4);
idx a(symbol("a"), 8), b(symbol("b"), 8);
ex e = -dirac_gamma(mu) * (2*color_T(a)) * 8 * color_T(b) * dirac_gamma(nu);
cout << e << endl;
// -> -16*(gamma~mu*gamma~nu)*(T.a*T.b)
...
@end example
As can be seen, GiNaC pulls out the overall commutative factor @samp{-16} and
groups the non-commutative factors (the gammas and the su(3) generators)
together while preserving the order of factors within each class (because
Clifford objects commutate with color objects). The resulting expression is a
@emph{commutative} product with two factors that are themselves non-commutative
products (@samp{gamma~mu*gamma~nu} and @samp{T.a*T.b}). For clarification,
parentheses are placed around the non-commutative products in the output.
@cindex @code{ncmul} (class)
Non-commutative products are internally represented by objects of the class
@code{ncmul}, as opposed to commutative products which are handled by the
@code{mul} class. You will normally not have to worry about this distinction,
though.
The advantage of this approach is that you never have to worry about using
(or forgetting to use) a special operator when constructing non-commutative
expressions. Also, non-commutative products in GiNaC are more intelligent
than in other computer algebra systems; they can, for example, automatically
canonicalize themselves according to rules specified in the implementation
of the non-commutative classes. The drawback is that to work with other than
the built-in algebras you have to implement new classes yourself. Both
symbols and user-defined functions can be specified as being non-commutative.
@cindex @code{return_type()}
@cindex @code{return_type_tinfo()}
Information about the commutativity of an object or expression can be
obtained with the two member functions
@example
unsigned ex::return_type() const;
return_type_t ex::return_type_tinfo() const;
@end example
The @code{return_type()} function returns one of three values (defined in
the header file @file{flags.h}), corresponding to three categories of
expressions in GiNaC:
@itemize @bullet
@item @code{return_types::commutative}: Commutates with everything. Most GiNaC
classes are of this kind.
@item @code{return_types::noncommutative}: Non-commutative, belonging to a
certain class of non-commutative objects which can be determined with the
@code{return_type_tinfo()} method. Expressions of this category commutate
with everything except @code{noncommutative} expressions of the same
class.
@item @code{return_types::noncommutative_composite}: Non-commutative, composed
of non-commutative objects of different classes. Expressions of this
category don't commutate with any other @code{noncommutative} or
@code{noncommutative_composite} expressions.
@end itemize
The @code{return_type_tinfo()} method returns an object of type
@code{return_type_t} that contains information about the type of the expression
and, if given, its representation label (see section on dirac gamma matrices for
more details). The objects of type @code{return_type_t} can be tested for
equality to test whether two expressions belong to the same category and
therefore may not commute.
Here are a couple of examples:
@cartouche
@multitable @columnfractions .6 .4
@item @strong{Expression} @tab @strong{@code{return_type()}}
@item @code{42} @tab @code{commutative}
@item @code{2*x-y} @tab @code{commutative}
@item @code{dirac_ONE()} @tab @code{noncommutative}
@item @code{dirac_gamma(mu)*dirac_gamma(nu)} @tab @code{noncommutative}
@item @code{2*color_T(a)} @tab @code{noncommutative}
@item @code{dirac_ONE()*color_T(a)} @tab @code{noncommutative_composite}
@end multitable
@end cartouche
A last note: With the exception of matrices, positive integer powers of
non-commutative objects are automatically expanded in GiNaC. For example,
@code{pow(a*b, 2)} becomes @samp{a*b*a*b} if @samp{a} and @samp{b} are
non-commutative expressions).
@cindex @code{clifford} (class)
@subsection Clifford algebra
Clifford algebras are supported in two flavours: Dirac gamma
matrices (more physical) and generic Clifford algebras (more
mathematical).
@cindex @code{dirac_gamma()}
@subsubsection Dirac gamma matrices
Dirac gamma matrices (note that GiNaC doesn't treat them
as matrices) are designated as @samp{gamma~mu} and satisfy
@samp{gamma~mu*gamma~nu + gamma~nu*gamma~mu = 2*eta~mu~nu} where
@samp{eta~mu~nu} is the Minkowski metric tensor. Dirac gammas are
constructed by the function
@example
ex dirac_gamma(const ex & mu, unsigned char rl = 0);
@end example
which takes two arguments: the index and a @dfn{representation label} in the
range 0 to 255 which is used to distinguish elements of different Clifford
algebras (this is also called a @dfn{spin line index}). Gammas with different
labels commutate with each other. The dimension of the index can be 4 or (in
the framework of dimensional regularization) any symbolic value. Spinor
indices on Dirac gammas are not supported in GiNaC.
@cindex @code{dirac_ONE()}
The unity element of a Clifford algebra is constructed by
@example
ex dirac_ONE(unsigned char rl = 0);
@end example
@strong{Please notice:} You must always use @code{dirac_ONE()} when referring to
multiples of the unity element, even though it's customary to omit it.
E.g. instead of @code{dirac_gamma(mu)*(dirac_slash(q,4)+m)} you have to
write @code{dirac_gamma(mu)*(dirac_slash(q,4)+m*dirac_ONE())}. Otherwise,
GiNaC will complain and/or produce incorrect results.
@cindex @code{dirac_gamma5()}
There is a special element @samp{gamma5} that commutates with all other
gammas, has a unit square, and in 4 dimensions equals
@samp{gamma~0 gamma~1 gamma~2 gamma~3}, provided by
@example
ex dirac_gamma5(unsigned char rl = 0);
@end example
@cindex @code{dirac_gammaL()}
@cindex @code{dirac_gammaR()}
The chiral projectors @samp{(1+/-gamma5)/2} are also available as proper
objects, constructed by
@example
ex dirac_gammaL(unsigned char rl = 0);
ex dirac_gammaR(unsigned char rl = 0);
@end example
They observe the relations @samp{gammaL^2 = gammaL}, @samp{gammaR^2 = gammaR},
and @samp{gammaL gammaR = gammaR gammaL = 0}.
@cindex @code{dirac_slash()}
Finally, the function
@example
ex dirac_slash(const ex & e, const ex & dim, unsigned char rl = 0);
@end example
creates a term that represents a contraction of @samp{e} with the Dirac
Lorentz vector (it behaves like a term of the form @samp{e.mu gamma~mu}
with a unique index whose dimension is given by the @code{dim} argument).
Such slashed expressions are printed with a trailing backslash, e.g. @samp{e\}.
In products of dirac gammas, superfluous unity elements are automatically
removed, squares are replaced by their values, and @samp{gamma5}, @samp{gammaL}
and @samp{gammaR} are moved to the front.
The @code{simplify_indexed()} function performs contractions in gamma strings,
for example
@example
@{
...
symbol a("a"), b("b"), D("D");
varidx mu(symbol("mu"), D);
ex e = dirac_gamma(mu) * dirac_slash(a, D)
* dirac_gamma(mu.toggle_variance());
cout << e << endl;
// -> gamma~mu*a\*gamma.mu
e = e.simplify_indexed();
cout << e << endl;
// -> -D*a\+2*a\
cout << e.subs(D == 4) << endl;
// -> -2*a\
...
@}
@end example
@cindex @code{dirac_trace()}
To calculate the trace of an expression containing strings of Dirac gammas
you use one of the functions
@example
ex dirac_trace(const ex & e, const std::set<unsigned char> & rls,
const ex & trONE = 4);
ex dirac_trace(const ex & e, const lst & rll, const ex & trONE = 4);
ex dirac_trace(const ex & e, unsigned char rl = 0, const ex & trONE = 4);
@end example
These functions take the trace over all gammas in the specified set @code{rls}
or list @code{rll} of representation labels, or the single label @code{rl};
gammas with other labels are left standing. The last argument to
@code{dirac_trace()} is the value to be returned for the trace of the unity
element, which defaults to 4.
The @code{dirac_trace()} function is a linear functional that is equal to the
ordinary matrix trace only in @math{D = 4} dimensions. In particular, the
functional is not cyclic in
@tex $D \ne 4$
@end tex
@ifnottex
@math{D != 4}
@end ifnottex
dimensions when acting on
expressions containing @samp{gamma5}, so it's not a proper trace. This
@samp{gamma5} scheme is described in greater detail in the article
@cite{The Role of gamma5 in Dimensional Regularization} (@ref{Bibliography}).
The value of the trace itself is also usually different in 4 and in
@tex $D \ne 4$
@end tex
@ifnottex
@math{D != 4}
@end ifnottex
dimensions:
@example
@{
// 4 dimensions
varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4), rho(symbol("rho"), 4);
ex e = dirac_gamma(mu) * dirac_gamma(nu) *
dirac_gamma(mu.toggle_variance()) * dirac_gamma(rho);
cout << dirac_trace(e).simplify_indexed() << endl;
// -> -8*eta~rho~nu
@}
...
@{
// D dimensions
symbol D("D");
varidx mu(symbol("mu"), D), nu(symbol("nu"), D), rho(symbol("rho"), D);
ex e = dirac_gamma(mu) * dirac_gamma(nu) *
dirac_gamma(mu.toggle_variance()) * dirac_gamma(rho);
cout << dirac_trace(e).simplify_indexed() << endl;
// -> 8*eta~rho~nu-4*eta~rho~nu*D
@}
@end example
Here is an example for using @code{dirac_trace()} to compute a value that
appears in the calculation of the one-loop vacuum polarization amplitude in
QED:
@example
@{
symbol q("q"), l("l"), m("m"), ldotq("ldotq"), D("D");
varidx mu(symbol("mu"), D), nu(symbol("nu"), D);
scalar_products sp;
sp.add(l, l, pow(l, 2));
sp.add(l, q, ldotq);
ex e = dirac_gamma(mu) *
(dirac_slash(l, D) + dirac_slash(q, D) + m * dirac_ONE()) *
dirac_gamma(mu.toggle_variance()) *
(dirac_slash(l, D) + m * dirac_ONE());
e = dirac_trace(e).simplify_indexed(sp);
e = e.collect(lst(l, ldotq, m));
cout << e << endl;
// -> (8-4*D)*l^2+(8-4*D)*ldotq+4*D*m^2
@}
@end example
The @code{canonicalize_clifford()} function reorders all gamma products that
appear in an expression to a canonical (but not necessarily simple) form.
You can use this to compare two expressions or for further simplifications:
@example
@{
varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4);
ex e = dirac_gamma(mu) * dirac_gamma(nu) + dirac_gamma(nu) * dirac_gamma(mu);
cout << e << endl;
// -> gamma~mu*gamma~nu+gamma~nu*gamma~mu
e = canonicalize_clifford(e);
cout << e << endl;
// -> 2*ONE*eta~mu~nu
@}
@end example
@cindex @code{clifford_unit()}
@subsubsection A generic Clifford algebra
A generic Clifford algebra, i.e. a
@tex $2^n$
@end tex
@ifnottex
2^n
@end ifnottex
dimensional algebra with
generators
@tex $e_k$
@end tex
@ifnottex
e_k
@end ifnottex
satisfying the identities
@tex
$e_i e_j + e_j e_i = M(i, j) + M(j, i)$
@end tex
@ifnottex
e~i e~j + e~j e~i = M(i, j) + M(j, i)
@end ifnottex
for some bilinear form (@code{metric})
@math{M(i, j)}, which may be non-symmetric (see arXiv:math.QA/9911180)
and contain symbolic entries. Such generators are created by the
function
@example
ex clifford_unit(const ex & mu, const ex & metr, unsigned char rl = 0);
@end example
where @code{mu} should be a @code{idx} (or descendant) class object
indexing the generators.
Parameter @code{metr} defines the metric @math{M(i, j)} and can be
represented by a square @code{matrix}, @code{tensormetric} or @code{indexed} class
object. In fact, any expression either with two free indices or without
indices at all is admitted as @code{metr}. In the later case an @code{indexed}
object with two newly created indices with @code{metr} as its
@code{op(0)} will be used.
Optional parameter @code{rl} allows to distinguish different
Clifford algebras, which will commute with each other.
Note that the call @code{clifford_unit(mu, minkmetric())} creates
something very close to @code{dirac_gamma(mu)}, although
@code{dirac_gamma} have more efficient simplification mechanism.
@cindex @code{clifford::get_metric()}
The method @code{clifford::get_metric()} returns a metric defining this
Clifford number.
If the matrix @math{M(i, j)} is in fact symmetric you may prefer to create
the Clifford algebra units with a call like that
@example
ex e = clifford_unit(mu, indexed(M, sy_symm(), i, j));
@end example
since this may yield some further automatic simplifications. Again, for a
metric defined through a @code{matrix} such a symmetry is detected
automatically.
Individual generators of a Clifford algebra can be accessed in several
ways. For example
@example
@{
...
idx i(symbol("i"), 4);
realsymbol s("s");
ex M = diag_matrix(lst(1, -1, 0, s));
ex e = clifford_unit(i, M);
ex e0 = e.subs(i == 0);
ex e1 = e.subs(i == 1);
ex e2 = e.subs(i == 2);
ex e3 = e.subs(i == 3);
...
@}
@end example
will produce four anti-commuting generators of a Clifford algebra with properties
@tex
$e_0^2=1 $, $e_1^2=-1$, $e_2^2=0$ and $e_3^2=s$.
@end tex
@ifnottex
@code{pow(e0, 2) = 1}, @code{pow(e1, 2) = -1}, @code{pow(e2, 2) = 0} and
@code{pow(e3, 2) = s}.
@end ifnottex
@cindex @code{lst_to_clifford()}
A similar effect can be achieved from the function
@example
ex lst_to_clifford(const ex & v, const ex & mu, const ex & metr,
unsigned char rl = 0);
ex lst_to_clifford(const ex & v, const ex & e);
@end example
which converts a list or vector
@tex
$v = (v^0, v^1, ..., v^n)$
@end tex
@ifnottex
@samp{v = (v~0, v~1, ..., v~n)}
@end ifnottex
into the
Clifford number
@tex
$v^0 e_0 + v^1 e_1 + ... + v^n e_n$
@end tex
@ifnottex
@samp{v~0 e.0 + v~1 e.1 + ... + v~n e.n}
@end ifnottex
with @samp{e.k}
directly supplied in the second form of the procedure. In the first form
the Clifford unit @samp{e.k} is generated by the call of
@code{clifford_unit(mu, metr, rl)}.
@cindex pseudo-vector
If the number of components supplied
by @code{v} exceeds the dimensionality of the Clifford unit @code{e} by
1 then function @code{lst_to_clifford()} uses the following
pseudo-vector representation:
@tex
$v^0 {\bf 1} + v^1 e_0 + v^2 e_1 + ... + v^{n+1} e_n$
@end tex
@ifnottex
@samp{v~0 ONE + v~1 e.0 + v~2 e.1 + ... + v~[n+1] e.n}
@end ifnottex
The previous code may be rewritten with the help of @code{lst_to_clifford()} as follows
@example
@{
...
idx i(symbol("i"), 4);
realsymbol s("s");
ex M = diag_matrix(lst(1, -1, 0, s));
ex e0 = lst_to_clifford(lst(1, 0, 0, 0), i, M);
ex e1 = lst_to_clifford(lst(0, 1, 0, 0), i, M);
ex e2 = lst_to_clifford(lst(0, 0, 1, 0), i, M);
ex e3 = lst_to_clifford(lst(0, 0, 0, 1), i, M);
...
@}
@end example
@cindex @code{clifford_to_lst()}
There is the inverse function
@example
lst clifford_to_lst(const ex & e, const ex & c, bool algebraic = true);
@end example
which takes an expression @code{e} and tries to find a list
@tex
$v = (v^0, v^1, ..., v^n)$
@end tex
@ifnottex
@samp{v = (v~0, v~1, ..., v~n)}
@end ifnottex
such that the expression is either vector
@tex
$e = v^0 c_0 + v^1 c_1 + ... + v^n c_n$
@end tex
@ifnottex
@samp{e = v~0 c.0 + v~1 c.1 + ... + v~n c.n}
@end ifnottex
or pseudo-vector
@tex
$v^0 {\bf 1} + v^1 e_0 + v^2 e_1 + ... + v^{n+1} e_n$
@end tex
@ifnottex
@samp{v~0 ONE + v~1 e.0 + v~2 e.1 + ... + v~[n+1] e.n}
@end ifnottex
with respect to the given Clifford units @code{c}. Here none of the
@samp{v~k} should contain Clifford units @code{c} (of course, this
may be impossible). This function can use an @code{algebraic} method
(default) or a symbolic one. With the @code{algebraic} method the
@samp{v~k} are calculated as
@tex
$(e c_k + c_k e)/c_k^2$. If $c_k^2$
@end tex
@ifnottex
@samp{(e c.k + c.k e)/pow(c.k, 2)}. If @samp{pow(c.k, 2)}
@end ifnottex
is zero or is not @code{numeric} for some @samp{k}
then the method will be automatically changed to symbolic. The same effect
is obtained by the assignment (@code{algebraic = false}) in the procedure call.
@cindex @code{clifford_prime()}
@cindex @code{clifford_star()}
@cindex @code{clifford_bar()}
There are several functions for (anti-)automorphisms of Clifford algebras:
@example
ex clifford_prime(const ex & e)
inline ex clifford_star(const ex & e) @{ return e.conjugate(); @}
inline ex clifford_bar(const ex & e) @{ return clifford_prime(e.conjugate()); @}
@end example
The automorphism of a Clifford algebra @code{clifford_prime()} simply
changes signs of all Clifford units in the expression. The reversion
of a Clifford algebra @code{clifford_star()} coincides with the
@code{conjugate()} method and effectively reverses the order of Clifford
units in any product. Finally the main anti-automorphism
of a Clifford algebra @code{clifford_bar()} is the composition of the
previous two, i.e. it makes the reversion and changes signs of all Clifford units
in a product. These functions correspond to the notations
@math{e'},
@tex
$e^*$
@end tex
@ifnottex
e*
@end ifnottex
and
@tex
$\overline{e}$
@end tex
@ifnottex
@code{\bar@{e@}}
@end ifnottex
used in Clifford algebra textbooks.
@cindex @code{clifford_norm()}
The function
@example
ex clifford_norm(const ex & e);
@end example
@cindex @code{clifford_inverse()}
calculates the norm of a Clifford number from the expression
@tex
$||e||^2 = e\overline{e}$.
@end tex
@ifnottex
@code{||e||^2 = e \bar@{e@}}
@end ifnottex
The inverse of a Clifford expression is returned by the function
@example
ex clifford_inverse(const ex & e);
@end example
which calculates it as
@tex
$e^{-1} = \overline{e}/||e||^2$.
@end tex
@ifnottex
@math{e^@{-1@} = \bar@{e@}/||e||^2}
@end ifnottex
If
@tex
$||e|| = 0$
@end tex
@ifnottex
@math{||e||=0}
@end ifnottex
then an exception is raised.
@cindex @code{remove_dirac_ONE()}
If a Clifford number happens to be a factor of
@code{dirac_ONE()} then we can convert it to a ``real'' (non-Clifford)
expression by the function
@example
ex remove_dirac_ONE(const ex & e);
@end example
@cindex @code{canonicalize_clifford()}
The function @code{canonicalize_clifford()} works for a
generic Clifford algebra in a similar way as for Dirac gammas.
The next provided function is
@cindex @code{clifford_moebius_map()}
@example
ex clifford_moebius_map(const ex & a, const ex & b, const ex & c,
const ex & d, const ex & v, const ex & G,
unsigned char rl = 0);
ex clifford_moebius_map(const ex & M, const ex & v, const ex & G,
unsigned char rl = 0);
@end example
It takes a list or vector @code{v} and makes the Moebius (conformal or
linear-fractional) transformation @samp{v -> (av+b)/(cv+d)} defined by
the matrix @samp{M = [[a, b], [c, d]]}. The parameter @code{G} defines
the metric of the surrounding (pseudo-)Euclidean space. This can be an
indexed object, tensormetric, matrix or a Clifford unit, in the later
case the optional parameter @code{rl} is ignored even if supplied.
Depending from the type of @code{v} the returned value of this function
is either a vector or a list holding vector's components.
@cindex @code{clifford_max_label()}
Finally the function
@example
char clifford_max_label(const ex & e, bool ignore_ONE = false);
@end example
can detect a presence of Clifford objects in the expression @code{e}: if
such objects are found it returns the maximal
@code{representation_label} of them, otherwise @code{-1}. The optional
parameter @code{ignore_ONE} indicates if @code{dirac_ONE} objects should
be ignored during the search.
LaTeX output for Clifford units looks like
@code{\clifford[1]@{e@}^@{@{\nu@}@}}, where @code{1} is the
@code{representation_label} and @code{\nu} is the index of the
corresponding unit. This provides a flexible typesetting with a suitable
definition of the @code{\clifford} command. For example, the definition
@example
\newcommand@{\clifford@}[1][]@{@}
@end example
typesets all Clifford units identically, while the alternative definition
@example
\newcommand@{\clifford@}[2][]@{\ifcase #1 #2\or \tilde@{#2@} \or \breve@{#2@} \fi@}
@end example
prints units with @code{representation_label=0} as
@tex
$e$,
@end tex
@ifnottex
@code{e},
@end ifnottex
with @code{representation_label=1} as
@tex
$\tilde{e}$
@end tex
@ifnottex
@code{\tilde@{e@}}
@end ifnottex
and with @code{representation_label=2} as
@tex
$\breve{e}$.
@end tex
@ifnottex
@code{\breve@{e@}}.
@end ifnottex
@cindex @code{color} (class)
@subsection Color algebra
@cindex @code{color_T()}
For computations in quantum chromodynamics, GiNaC implements the base elements
and structure constants of the su(3) Lie algebra (color algebra). The base
elements @math{T_a} are constructed by the function
@example
ex color_T(const ex & a, unsigned char rl = 0);
@end example
which takes two arguments: the index and a @dfn{representation label} in the
range 0 to 255 which is used to distinguish elements of different color
algebras. Objects with different labels commutate with each other. The
dimension of the index must be exactly 8 and it should be of class @code{idx},
not @code{varidx}.
@cindex @code{color_ONE()}
The unity element of a color algebra is constructed by
@example
ex color_ONE(unsigned char rl = 0);
@end example
@strong{Please notice:} You must always use @code{color_ONE()} when referring to
multiples of the unity element, even though it's customary to omit it.
E.g. instead of @code{color_T(a)*(color_T(b)*indexed(X,b)+1)} you have to
write @code{color_T(a)*(color_T(b)*indexed(X,b)+color_ONE())}. Otherwise,
GiNaC may produce incorrect results.
@cindex @code{color_d()}
@cindex @code{color_f()}
The functions
@example
ex color_d(const ex & a, const ex & b, const ex & c);
ex color_f(const ex & a, const ex & b, const ex & c);
@end example
create the symmetric and antisymmetric structure constants @math{d_abc} and
@math{f_abc} which satisfy @math{@{T_a, T_b@} = 1/3 delta_ab + d_abc T_c}
and @math{[T_a, T_b] = i f_abc T_c}.
These functions evaluate to their numerical values,
if you supply numeric indices to them. The index values should be in
the range from 1 to 8, not from 0 to 7. This departure from usual conventions
goes along better with the notations used in physical literature.
@cindex @code{color_h()}
There's an additional function
@example
ex color_h(const ex & a, const ex & b, const ex & c);
@end example
which returns the linear combination @samp{color_d(a, b, c)+I*color_f(a, b, c)}.
The function @code{simplify_indexed()} performs some simplifications on
expressions containing color objects:
@example
@{
...
idx a(symbol("a"), 8), b(symbol("b"), 8), c(symbol("c"), 8),
k(symbol("k"), 8), l(symbol("l"), 8);
e = color_d(a, b, l) * color_f(a, b, k);
cout << e.simplify_indexed() << endl;
// -> 0
e = color_d(a, b, l) * color_d(a, b, k);
cout << e.simplify_indexed() << endl;
// -> 5/3*delta.k.l
e = color_f(l, a, b) * color_f(a, b, k);
cout << e.simplify_indexed() << endl;
// -> 3*delta.k.l
e = color_h(a, b, c) * color_h(a, b, c);
cout << e.simplify_indexed() << endl;
// -> -32/3
e = color_h(a, b, c) * color_T(b) * color_T(c);
cout << e.simplify_indexed() << endl;
// -> -2/3*T.a
e = color_h(a, b, c) * color_T(a) * color_T(b) * color_T(c);
cout << e.simplify_indexed() << endl;
// -> -8/9*ONE
e = color_T(k) * color_T(a) * color_T(b) * color_T(k);
cout << e.simplify_indexed() << endl;
// -> 1/4*delta.b.a*ONE-1/6*T.a*T.b
...
@end example
@cindex @code{color_trace()}
To calculate the trace of an expression containing color objects you use one
of the functions
@example
ex color_trace(const ex & e, const std::set<unsigned char> & rls);
ex color_trace(const ex & e, const lst & rll);
ex color_trace(const ex & e, unsigned char rl = 0);
@end example
These functions take the trace over all color @samp{T} objects in the
specified set @code{rls} or list @code{rll} of representation labels, or the
single label @code{rl}; @samp{T}s with other labels are left standing. For
example:
@example
...
e = color_trace(4 * color_T(a) * color_T(b) * color_T(c));
cout << e << endl;
// -> -I*f.a.c.b+d.a.c.b
@}
@end example
@node Hash maps, Methods and functions, Non-commutative objects, Basic concepts
@c node-name, next, previous, up
@section Hash Maps
@cindex hash maps
@cindex @code{exhashmap} (class)
For your convenience, GiNaC offers the container template @code{exhashmap<T>}
that can be used as a drop-in replacement for the STL
@code{std::map<ex, T, ex_is_less>}, using hash tables to provide faster,
typically constant-time, element look-up than @code{map<>}.
@code{exhashmap<>} supports all @code{map<>} members and operations, with the
following differences:
@itemize @bullet
@item
no @code{lower_bound()} and @code{upper_bound()} methods
@item
no reverse iterators, no @code{rbegin()}/@code{rend()}
@item
no @code{operator<(exhashmap, exhashmap)}
@item
the comparison function object @code{key_compare} is hardcoded to
@code{ex_is_less}
@item
the constructor @code{exhashmap(size_t n)} allows specifying the minimum
initial hash table size (the actual table size after construction may be
larger than the specified value)
@item
the method @code{size_t bucket_count()} returns the current size of the hash
table
@item
@code{insert()} and @code{erase()} operations invalidate all iterators
@end itemize
@node Methods and functions, Information about expressions, Hash maps, Top
@c node-name, next, previous, up
@chapter Methods and functions
@cindex polynomial
In this chapter the most important algorithms provided by GiNaC will be
described. Some of them are implemented as functions on expressions,
others are implemented as methods provided by expression objects. If
they are methods, there exists a wrapper function around it, so you can
alternatively call it in a functional way as shown in the simple
example:
@example
...
cout << "As method: " << sin(1).evalf() << endl;
cout << "As function: " << evalf(sin(1)) << endl;
...
@end example
@cindex @code{subs()}
The general rule is that wherever methods accept one or more parameters
(@var{arg1}, @var{arg2}, @dots{}) the order of arguments the function
wrapper accepts is the same but preceded by the object to act on
(@var{object}, @var{arg1}, @var{arg2}, @dots{}). This approach is the
most natural one in an OO model but it may lead to confusion for MapleV
users because where they would type @code{A:=x+1; subs(x=2,A);} GiNaC
would require @code{A=x+1; subs(A,x==2);} (after proper declaration of
@code{A} and @code{x}). On the other hand, since MapleV returns 3 on
@code{A:=x^2+3; coeff(A,x,0);} (GiNaC: @code{A=pow(x,2)+3;
coeff(A,x,0);}) it is clear that MapleV is not trying to be consistent
here. Also, users of MuPAD will in most cases feel more comfortable
with GiNaC's convention. All function wrappers are implemented
as simple inline functions which just call the corresponding method and
are only provided for users uncomfortable with OO who are dead set to
avoid method invocations. Generally, nested function wrappers are much
harder to read than a sequence of methods and should therefore be
avoided if possible. On the other hand, not everything in GiNaC is a
method on class @code{ex} and sometimes calling a function cannot be
avoided.
@menu
* Information about expressions::
* Numerical evaluation::
* Substituting expressions::
* Pattern matching and advanced substitutions::
* Applying a function on subexpressions::
* Visitors and tree traversal::
* Polynomial arithmetic:: Working with polynomials.
* Rational expressions:: Working with rational functions.
* Symbolic differentiation::
* Series expansion:: Taylor and Laurent expansion.
* Symmetrization::
* Built-in functions:: List of predefined mathematical functions.
* Multiple polylogarithms::
* Complex expressions::
* Solving linear systems of equations::
* Input/output:: Input and output of expressions.
@end menu
@node Information about expressions, Numerical evaluation, Methods and functions, Methods and functions
@c node-name, next, previous, up
@section Getting information about expressions
@subsection Checking expression types
@cindex @code{is_a<@dots{}>()}
@cindex @code{is_exactly_a<@dots{}>()}
@cindex @code{ex_to<@dots{}>()}
@cindex Converting @code{ex} to other classes
@cindex @code{info()}
@cindex @code{return_type()}
@cindex @code{return_type_tinfo()}
Sometimes it's useful to check whether a given expression is a plain number,
a sum, a polynomial with integer coefficients, or of some other specific type.
GiNaC provides a couple of functions for this:
@example
bool is_a<T>(const ex & e);
bool is_exactly_a<T>(const ex & e);
bool ex::info(unsigned flag);
unsigned ex::return_type() const;
return_type_t ex::return_type_tinfo() const;
@end example
When the test made by @code{is_a<T>()} returns true, it is safe to call
one of the functions @code{ex_to<T>()}, where @code{T} is one of the
class names (@xref{The class hierarchy}, for a list of all classes). For
example, assuming @code{e} is an @code{ex}:
@example
@{
@dots{}
if (is_a<numeric>(e))
numeric n = ex_to<numeric>(e);
@dots{}
@}
@end example
@code{is_a<T>(e)} allows you to check whether the top-level object of
an expression @samp{e} is an instance of the GiNaC class @samp{T}
(@xref{The class hierarchy}, for a list of all classes). This is most useful,
e.g., for checking whether an expression is a number, a sum, or a product:
@example
@{
symbol x("x");
ex e1 = 42;
ex e2 = 4*x - 3;
is_a<numeric>(e1); // true
is_a<numeric>(e2); // false
is_a<add>(e1); // false
is_a<add>(e2); // true
is_a<mul>(e1); // false
is_a<mul>(e2); // false
@}
@end example
In contrast, @code{is_exactly_a<T>(e)} allows you to check whether the
top-level object of an expression @samp{e} is an instance of the GiNaC
class @samp{T}, not including parent classes.
The @code{info()} method is used for checking certain attributes of
expressions. The possible values for the @code{flag} argument are defined
in @file{ginac/flags.h}, the most important being explained in the following
table:
@cartouche
@multitable @columnfractions .30 .70
@item @strong{Flag} @tab @strong{Returns true if the object is@dots{}}
@item @code{numeric}
@tab @dots{}a number (same as @code{is_a<numeric>(...)})
@item @code{real}
@tab @dots{}a real number, symbol or constant (i.e. is not complex)
@item @code{rational}
@tab @dots{}an exact rational number (integers are rational, too)
@item @code{integer}
@tab @dots{}a (non-complex) integer
@item @code{crational}
@tab @dots{}an exact (complex) rational number (such as @math{2/3+7/2*I})
@item @code{cinteger}
@tab @dots{}a (complex) integer (such as @math{2-3*I})
@item @code{positive}
@tab @dots{}not complex and greater than 0
@item @code{negative}
@tab @dots{}not complex and less than 0
@item @code{nonnegative}
@tab @dots{}not complex and greater than or equal to 0
@item @code{posint}
@tab @dots{}an integer greater than 0
@item @code{negint}
@tab @dots{}an integer less than 0
@item @code{nonnegint}
@tab @dots{}an integer greater than or equal to 0
@item @code{even}
@tab @dots{}an even integer
@item @code{odd}
@tab @dots{}an odd integer
@item @code{prime}
@tab @dots{}a prime integer (probabilistic primality test)
@item @code{relation}
@tab @dots{}a relation (same as @code{is_a<relational>(...)})
@item @code{relation_equal}
@tab @dots{}a @code{==} relation
@item @code{relation_not_equal}
@tab @dots{}a @code{!=} relation
@item @code{relation_less}
@tab @dots{}a @code{<} relation
@item @code{relation_less_or_equal}
@tab @dots{}a @code{<=} relation
@item @code{relation_greater}
@tab @dots{}a @code{>} relation
@item @code{relation_greater_or_equal}
@tab @dots{}a @code{>=} relation
@item @code{symbol}
@tab @dots{}a symbol (same as @code{is_a<symbol>(...)})
@item @code{list}
@tab @dots{}a list (same as @code{is_a<lst>(...)})
@item @code{polynomial}
@tab @dots{}a polynomial (i.e. only consists of sums and products of numbers and symbols with positive integer powers)
@item @code{integer_polynomial}
@tab @dots{}a polynomial with (non-complex) integer coefficients
@item @code{cinteger_polynomial}
@tab @dots{}a polynomial with (possibly complex) integer coefficients (such as @math{2-3*I})
@item @code{rational_polynomial}
@tab @dots{}a polynomial with (non-complex) rational coefficients
@item @code{crational_polynomial}
@tab @dots{}a polynomial with (possibly complex) rational coefficients (such as @math{2/3+7/2*I})
@item @code{rational_function}
@tab @dots{}a rational function (@math{x+y}, @math{z/(x+y)})
@item @code{algebraic}
@tab @dots{}an algebraic object (@math{sqrt(2)}, @math{sqrt(x)-1})
@end multitable
@end cartouche
To determine whether an expression is commutative or non-commutative and if
so, with which other expressions it would commutate, you use the methods
@code{return_type()} and @code{return_type_tinfo()}. @xref{Non-commutative objects},
for an explanation of these.
@subsection Accessing subexpressions
@cindex container
Many GiNaC classes, like @code{add}, @code{mul}, @code{lst}, and
@code{function}, act as containers for subexpressions. For example, the
subexpressions of a sum (an @code{add} object) are the individual terms,
and the subexpressions of a @code{function} are the function's arguments.
@cindex @code{nops()}
@cindex @code{op()}
GiNaC provides several ways of accessing subexpressions. The first way is to
use the two methods
@example
size_t ex::nops();
ex ex::op(size_t i);
@end example
@code{nops()} determines the number of subexpressions (operands) contained
in the expression, while @code{op(i)} returns the @code{i}-th
(0..@code{nops()-1}) subexpression. In the case of a @code{power} object,
@code{op(0)} will return the basis and @code{op(1)} the exponent. For
@code{indexed} objects, @code{op(0)} is the base expression and @code{op(i)},
@math{i>0} are the indices.
@cindex iterators
@cindex @code{const_iterator}
The second way to access subexpressions is via the STL-style random-access
iterator class @code{const_iterator} and the methods
@example
const_iterator ex::begin();
const_iterator ex::end();
@end example
@code{begin()} returns an iterator referring to the first subexpression;
@code{end()} returns an iterator which is one-past the last subexpression.
If the expression has no subexpressions, then @code{begin() == end()}. These
iterators can also be used in conjunction with non-modifying STL algorithms.
Here is an example that (non-recursively) prints the subexpressions of a
given expression in three different ways:
@example
@{
ex e = ...
// with nops()/op()
for (size_t i = 0; i != e.nops(); ++i)
cout << e.op(i) << endl;
// with iterators
for (const_iterator i = e.begin(); i != e.end(); ++i)
cout << *i << endl;
// with iterators and STL copy()
std::copy(e.begin(), e.end(), std::ostream_iterator<ex>(cout, "\n"));
@}
@end example
@cindex @code{const_preorder_iterator}
@cindex @code{const_postorder_iterator}
@code{op()}/@code{nops()} and @code{const_iterator} only access an
expression's immediate children. GiNaC provides two additional iterator
classes, @code{const_preorder_iterator} and @code{const_postorder_iterator},
that iterate over all objects in an expression tree, in preorder or postorder,
respectively. They are STL-style forward iterators, and are created with the
methods
@example
const_preorder_iterator ex::preorder_begin();
const_preorder_iterator ex::preorder_end();
const_postorder_iterator ex::postorder_begin();
const_postorder_iterator ex::postorder_end();
@end example
The following example illustrates the differences between
@code{const_iterator}, @code{const_preorder_iterator}, and
@code{const_postorder_iterator}:
@example
@{
symbol A("A"), B("B"), C("C");
ex e = lst(lst(A, B), C);
std::copy(e.begin(), e.end(),
std::ostream_iterator<ex>(cout, "\n"));
// @{A,B@}
// C
std::copy(e.preorder_begin(), e.preorder_end(),
std::ostream_iterator<ex>(cout, "\n"));
// @{@{A,B@},C@}
// @{A,B@}
// A
// B
// C
std::copy(e.postorder_begin(), e.postorder_end(),
std::ostream_iterator<ex>(cout, "\n"));
// A
// B
// @{A,B@}
// C
// @{@{A,B@},C@}
@}
@end example
@cindex @code{relational} (class)
Finally, the left-hand side and right-hand side expressions of objects of
class @code{relational} (and only of these) can also be accessed with the
methods
@example
ex ex::lhs();
ex ex::rhs();
@end example
@subsection Comparing expressions
@cindex @code{is_equal()}
@cindex @code{is_zero()}
Expressions can be compared with the usual C++ relational operators like
@code{==}, @code{>}, and @code{<} but if the expressions contain symbols,
the result is usually not determinable and the result will be @code{false},
except in the case of the @code{!=} operator. You should also be aware that
GiNaC will only do the most trivial test for equality (subtracting both
expressions), so something like @code{(pow(x,2)+x)/x==x+1} will return
@code{false}.
Actually, if you construct an expression like @code{a == b}, this will be
represented by an object of the @code{relational} class (@pxref{Relations})
which is not evaluated until (explicitly or implicitly) cast to a @code{bool}.
There are also two methods
@example
bool ex::is_equal(const ex & other);
bool ex::is_zero();
@end example
for checking whether one expression is equal to another, or equal to zero,
respectively. See also the method @code{ex::is_zero_matrix()},
@pxref{Matrices}.
@subsection Ordering expressions
@cindex @code{ex_is_less} (class)
@cindex @code{ex_is_equal} (class)
@cindex @code{compare()}
Sometimes it is necessary to establish a mathematically well-defined ordering
on a set of arbitrary expressions, for example to use expressions as keys
in a @code{std::map<>} container, or to bring a vector of expressions into
a canonical order (which is done internally by GiNaC for sums and products).
The operators @code{<}, @code{>} etc. described in the last section cannot
be used for this, as they don't implement an ordering relation in the
mathematical sense. In particular, they are not guaranteed to be
antisymmetric: if @samp{a} and @samp{b} are different expressions, and
@code{a < b} yields @code{false}, then @code{b < a} doesn't necessarily
yield @code{true}.
By default, STL classes and algorithms use the @code{<} and @code{==}
operators to compare objects, which are unsuitable for expressions, but GiNaC
provides two functors that can be supplied as proper binary comparison
predicates to the STL:
@example
class ex_is_less : public std::binary_function<ex, ex, bool> @{
public:
bool operator()(const ex &lh, const ex &rh) const;
@};
class ex_is_equal : public std::binary_function<ex, ex, bool> @{
public:
bool operator()(const ex &lh, const ex &rh) const;
@};
@end example
For example, to define a @code{map} that maps expressions to strings you
have to use
@example
std::map<ex, std::string, ex_is_less> myMap;
@end example
Omitting the @code{ex_is_less} template parameter will introduce spurious
bugs because the map operates improperly.
Other examples for the use of the functors:
@example
std::vector<ex> v;
// fill vector
...
// sort vector
std::sort(v.begin(), v.end(), ex_is_less());
// count the number of expressions equal to '1'
unsigned num_ones = std::count_if(v.begin(), v.end(),
std::bind2nd(ex_is_equal(), 1));
@end example
The implementation of @code{ex_is_less} uses the member function
@example
int ex::compare(const ex & other) const;
@end example
which returns @math{0} if @code{*this} and @code{other} are equal, @math{-1}
if @code{*this} sorts before @code{other}, and @math{1} if @code{*this} sorts
after @code{other}.
@node Numerical evaluation, Substituting expressions, Information about expressions, Methods and functions
@c node-name, next, previous, up
@section Numerical evaluation
@cindex @code{evalf()}
GiNaC keeps algebraic expressions, numbers and constants in their exact form.
To evaluate them using floating-point arithmetic you need to call
@example
ex ex::evalf(int level = 0) const;
@end example
@cindex @code{Digits}
The accuracy of the evaluation is controlled by the global object @code{Digits}
which can be assigned an integer value. The default value of @code{Digits}
is 17. @xref{Numbers}, for more information and examples.
To evaluate an expression to a @code{double} floating-point number you can
call @code{evalf()} followed by @code{numeric::to_double()}, like this:
@example
@{
// Approximate sin(x/Pi)
symbol x("x");
ex e = series(sin(x/Pi), x == 0, 6);
// Evaluate numerically at x=0.1
ex f = evalf(e.subs(x == 0.1));
// ex_to<numeric> is an unsafe cast, so check the type first
if (is_a<numeric>(f)) @{
double d = ex_to<numeric>(f).to_double();
cout << d << endl;
// -> 0.0318256
@} else
// error
@}
@end example
@node Substituting expressions, Pattern matching and advanced substitutions, Numerical evaluation, Methods and functions
@c node-name, next, previous, up
@section Substituting expressions
@cindex @code{subs()}
Algebraic objects inside expressions can be replaced with arbitrary
expressions via the @code{.subs()} method:
@example
ex ex::subs(const ex & e, unsigned options = 0);
ex ex::subs(const exmap & m, unsigned options = 0);
ex ex::subs(const lst & syms, const lst & repls, unsigned options = 0);
@end example
In the first form, @code{subs()} accepts a relational of the form
@samp{object == expression} or a @code{lst} of such relationals:
@example
@{
symbol x("x"), y("y");
ex e1 = 2*x^2-4*x+3;
cout << "e1(7) = " << e1.subs(x == 7) << endl;
// -> 73
ex e2 = x*y + x;
cout << "e2(-2, 4) = " << e2.subs(lst(x == -2, y == 4)) << endl;
// -> -10
@}
@end example
If you specify multiple substitutions, they are performed in parallel, so e.g.
@code{subs(lst(x == y, y == x))} exchanges @samp{x} and @samp{y}.
The second form of @code{subs()} takes an @code{exmap} object which is a
pair associative container that maps expressions to expressions (currently
implemented as a @code{std::map}). This is the most efficient one of the
three @code{subs()} forms and should be used when the number of objects to
be substituted is large or unknown.
Using this form, the second example from above would look like this:
@example
@{
symbol x("x"), y("y");
ex e2 = x*y + x;
exmap m;
m[x] = -2;
m[y] = 4;
cout << "e2(-2, 4) = " << e2.subs(m) << endl;
@}
@end example
The third form of @code{subs()} takes two lists, one for the objects to be
replaced and one for the expressions to be substituted (both lists must
contain the same number of elements). Using this form, you would write
@example
@{
symbol x("x"), y("y");
ex e2 = x*y + x;
cout << "e2(-2, 4) = " << e2.subs(lst(x, y), lst(-2, 4)) << endl;
@}
@end example
The optional last argument to @code{subs()} is a combination of
@code{subs_options} flags. There are three options available:
@code{subs_options::no_pattern} disables pattern matching, which makes
large @code{subs()} operations significantly faster if you are not using
patterns. The second option, @code{subs_options::algebraic} enables
algebraic substitutions in products and powers.
@xref{Pattern matching and advanced substitutions}, for more information
about patterns and algebraic substitutions. The third option,
@code{subs_options::no_index_renaming} disables the feature that dummy
indices are renamed if the substitution could give a result in which a
dummy index occurs more than two times. This is sometimes necessary if
you want to use @code{subs()} to rename your dummy indices.
@code{subs()} performs syntactic substitution of any complete algebraic
object; it does not try to match sub-expressions as is demonstrated by the
following example:
@example
@{
symbol x("x"), y("y"), z("z");
ex e1 = pow(x+y, 2);
cout << e1.subs(x+y == 4) << endl;
// -> 16
ex e2 = sin(x)*sin(y)*cos(x);
cout << e2.subs(sin(x) == cos(x)) << endl;
// -> cos(x)^2*sin(y)
ex e3 = x+y+z;
cout << e3.subs(x+y == 4) << endl;
// -> x+y+z
// (and not 4+z as one might expect)
@}
@end example
A more powerful form of substitution using wildcards is described in the
next section.
@node Pattern matching and advanced substitutions, Applying a function on subexpressions, Substituting expressions, Methods and functions
@c node-name, next, previous, up
@section Pattern matching and advanced substitutions
@cindex @code{wildcard} (class)
@cindex Pattern matching
GiNaC allows the use of patterns for checking whether an expression is of a
certain form or contains subexpressions of a certain form, and for
substituting expressions in a more general way.
A @dfn{pattern} is an algebraic expression that optionally contains wildcards.
A @dfn{wildcard} is a special kind of object (of class @code{wildcard}) that
represents an arbitrary expression. Every wildcard has a @dfn{label} which is
an unsigned integer number to allow having multiple different wildcards in a
pattern. Wildcards are printed as @samp{$label} (this is also the way they
are specified in @command{ginsh}). In C++ code, wildcard objects are created
with the call
@example
ex wild(unsigned label = 0);
@end example
which is simply a wrapper for the @code{wildcard()} constructor with a shorter
name.
Some examples for patterns:
@multitable @columnfractions .5 .5
@item @strong{Constructed as} @tab @strong{Output as}
@item @code{wild()} @tab @samp{$0}
@item @code{pow(x,wild())} @tab @samp{x^$0}
@item @code{atan2(wild(1),wild(2))} @tab @samp{atan2($1,$2)}
@item @code{indexed(A,idx(wild(),3))} @tab @samp{A.$0}
@end multitable
Notes:
@itemize @bullet
@item Wildcards behave like symbols and are subject to the same algebraic
rules. E.g., @samp{$0+2*$0} is automatically transformed to @samp{3*$0}.
@item As shown in the last example, to use wildcards for indices you have to
use them as the value of an @code{idx} object. This is because indices must
always be of class @code{idx} (or a subclass).
@item Wildcards only represent expressions or subexpressions. It is not
possible to use them as placeholders for other properties like index
dimension or variance, representation labels, symmetry of indexed objects
etc.
@item Because wildcards are commutative, it is not possible to use wildcards
as part of noncommutative products.
@item A pattern does not have to contain wildcards. @samp{x} and @samp{x+y}
are also valid patterns.
@end itemize
@subsection Matching expressions
@cindex @code{match()}
The most basic application of patterns is to check whether an expression
matches a given pattern. This is done by the function
@example
bool ex::match(const ex & pattern);
bool ex::match(const ex & pattern, exmap& repls);
@end example
This function returns @code{true} when the expression matches the pattern
and @code{false} if it doesn't. If used in the second form, the actual
subexpressions matched by the wildcards get returned in the associative
array @code{repls} with @samp{wildcard} as a key. If @code{match()}
returns false, @code{repls} remains unmodified.
The matching algorithm works as follows:
@itemize
@item A single wildcard matches any expression. If one wildcard appears
multiple times in a pattern, it must match the same expression in all
places (e.g. @samp{$0} matches anything, and @samp{$0*($0+1)} matches
@samp{x*(x+1)} but not @samp{x*(y+1)}).
@item If the expression is not of the same class as the pattern, the match
fails (i.e. a sum only matches a sum, a function only matches a function,
etc.).
@item If the pattern is a function, it only matches the same function
(i.e. @samp{sin($0)} matches @samp{sin(x)} but doesn't match @samp{exp(x)}).
@item Except for sums and products, the match fails if the number of
subexpressions (@code{nops()}) is not equal to the number of subexpressions
of the pattern.
@item If there are no subexpressions, the expressions and the pattern must
be equal (in the sense of @code{is_equal()}).
@item Except for sums and products, each subexpression (@code{op()}) must
match the corresponding subexpression of the pattern.
@end itemize
Sums (@code{add}) and products (@code{mul}) are treated in a special way to
account for their commutativity and associativity:
@itemize
@item If the pattern contains a term or factor that is a single wildcard,
this one is used as the @dfn{global wildcard}. If there is more than one
such wildcard, one of them is chosen as the global wildcard in a random
way.
@item Every term/factor of the pattern, except the global wildcard, is
matched against every term of the expression in sequence. If no match is
found, the whole match fails. Terms that did match are not considered in
further matches.
@item If there are no unmatched terms left, the match succeeds. Otherwise
the match fails unless there is a global wildcard in the pattern, in
which case this wildcard matches the remaining terms.
@end itemize
In general, having more than one single wildcard as a term of a sum or a
factor of a product (such as @samp{a+$0+$1}) will lead to unpredictable or
ambiguous results.
Here are some examples in @command{ginsh} to demonstrate how it works (the
@code{match()} function in @command{ginsh} returns @samp{FAIL} if the
match fails, and the list of wildcard replacements otherwise):
@example
> match((x+y)^a,(x+y)^a);
@{@}
> match((x+y)^a,(x+y)^b);
FAIL
> match((x+y)^a,$1^$2);
@{$1==x+y,$2==a@}
> match((x+y)^a,$1^$1);
FAIL
> match((x+y)^(x+y),$1^$1);
@{$1==x+y@}
> match((x+y)^(x+y),$1^$2);
@{$1==x+y,$2==x+y@}
> match((a+b)*(a+c),($1+b)*($1+c));
@{$1==a@}
> match((a+b)*(a+c),(a+$1)*(a+$2));
@{$1==b,$2==c@}
(Unpredictable. The result might also be [$1==c,$2==b].)
> match((a+b)*(a+c),($1+$2)*($1+$3));
(The result is undefined. Due to the sequential nature of the algorithm
and the re-ordering of terms in GiNaC, the match for the first factor
may be @{$1==a,$2==b@} in which case the match for the second factor
succeeds, or it may be @{$1==b,$2==a@} which causes the second match to
fail.)
> match(a*(x+y)+a*z+b,a*$1+$2);
(This is also ambiguous and may return either @{$1==z,$2==a*(x+y)+b@} or
@{$1=x+y,$2=a*z+b@}.)
> match(a+b+c+d+e+f,c);
FAIL
> match(a+b+c+d+e+f,c+$0);
@{$0==a+e+b+f+d@}
> match(a+b+c+d+e+f,c+e+$0);
@{$0==a+b+f+d@}
> match(a+b,a+b+$0);
@{$0==0@}
> match(a*b^2,a^$1*b^$2);
FAIL
(The matching is syntactic, not algebraic, and "a" doesn't match "a^$1"
even though a==a^1.)
> match(x*atan2(x,x^2),$0*atan2($0,$0^2));
@{$0==x@}
> match(atan2(y,x^2),atan2(y,$0));
@{$0==x^2@}
@end example
@subsection Matching parts of expressions
@cindex @code{has()}
A more general way to look for patterns in expressions is provided by the
member function
@example
bool ex::has(const ex & pattern);
@end example
This function checks whether a pattern is matched by an expression itself or
by any of its subexpressions.
Again some examples in @command{ginsh} for illustration (in @command{ginsh},
@code{has()} returns @samp{1} for @code{true} and @samp{0} for @code{false}):
@example
> has(x*sin(x+y+2*a),y);
1
> has(x*sin(x+y+2*a),x+y);
0
(This is because in GiNaC, "x+y" is not a subexpression of "x+y+2*a" (which
has the subexpressions "x", "y" and "2*a".)
> has(x*sin(x+y+2*a),x+y+$1);
1
(But this is possible.)
> has(x*sin(2*(x+y)+2*a),x+y);
0
(This fails because "2*(x+y)" automatically gets converted to "2*x+2*y" of
which "x+y" is not a subexpression.)
> has(x+1,x^$1);
0
(Although x^1==x and x^0==1, neither "x" nor "1" are actually of the form
"x^something".)
> has(4*x^2-x+3,$1*x);
1
> has(4*x^2+x+3,$1*x);
0
(Another possible pitfall. The first expression matches because the term
"-x" has the form "(-1)*x" in GiNaC. To check whether a polynomial
contains a linear term you should use the coeff() function instead.)
@end example
@cindex @code{find()}
The method
@example
bool ex::find(const ex & pattern, exset& found);
@end example
works a bit like @code{has()} but it doesn't stop upon finding the first
match. Instead, it appends all found matches to the specified list. If there
are multiple occurrences of the same expression, it is entered only once to
the list. @code{find()} returns false if no matches were found (in
@command{ginsh}, it returns an empty list):
@example
> find(1+x+x^2+x^3,x);
@{x@}
> find(1+x+x^2+x^3,y);
@{@}
> find(1+x+x^2+x^3,x^$1);
@{x^3,x^2@}
(Note the absence of "x".)
> expand((sin(x)+sin(y))*(a+b));
sin(y)*a+sin(x)*b+sin(x)*a+sin(y)*b
> find(%,sin($1));
@{sin(y),sin(x)@}
@end example
@subsection Substituting expressions
@cindex @code{subs()}
Probably the most useful application of patterns is to use them for
substituting expressions with the @code{subs()} method. Wildcards can be
used in the search patterns as well as in the replacement expressions, where
they get replaced by the expressions matched by them. @code{subs()} doesn't
know anything about algebra; it performs purely syntactic substitutions.
Some examples:
@example
> subs(a^2+b^2+(x+y)^2,$1^2==$1^3);
b^3+a^3+(x+y)^3
> subs(a^4+b^4+(x+y)^4,$1^2==$1^3);
b^4+a^4+(x+y)^4
> subs((a+b+c)^2,a+b==x);
(a+b+c)^2
> subs((a+b+c)^2,a+b+$1==x+$1);
(x+c)^2
> subs(a+2*b,a+b==x);
a+2*b
> subs(4*x^3-2*x^2+5*x-1,x==a);
-1+5*a-2*a^2+4*a^3
> subs(4*x^3-2*x^2+5*x-1,x^$0==a^$0);
-1+5*x-2*a^2+4*a^3
> subs(sin(1+sin(x)),sin($1)==cos($1));
cos(1+cos(x))
> expand(subs(a*sin(x+y)^2+a*cos(x+y)^2+b,cos($1)^2==1-sin($1)^2));
a+b
@end example
The last example would be written in C++ in this way:
@example
@{
symbol a("a"), b("b"), x("x"), y("y");
e = a*pow(sin(x+y), 2) + a*pow(cos(x+y), 2) + b;
e = e.subs(pow(cos(wild()), 2) == 1-pow(sin(wild()), 2));
cout << e.expand() << endl;
// -> a+b
@}
@end example
@subsection The option algebraic
Both @code{has()} and @code{subs()} take an optional argument to pass them
extra options. This section describes what happens if you give the former
the option @code{has_options::algebraic} or the latter
@code{subs_options::algebraic}. In that case the matching condition for
powers and multiplications is changed in such a way that they become
more intuitive. Intuition says that @code{x*y} is a part of @code{x*y*z}.
If you use these options you will find that
@code{(x*y*z).has(x*y, has_options::algebraic)} indeed returns true.
Besides matching some of the factors of a product also powers match as
often as is possible without getting negative exponents. For example
@code{(x^5*y^2*z).subs(x^2*y^2==c, subs_options::algebraic)} will return
@code{x*c^2*z}. This also works with negative powers:
@code{(x^(-3)*y^(-2)*z).subs(1/(x*y)==c, subs_options::algebraic)} will
return @code{x^(-1)*c^2*z}.
@strong{Please notice:} this only works for multiplications
and not for locating @code{x+y} within @code{x+y+z}.
@node Applying a function on subexpressions, Visitors and tree traversal, Pattern matching and advanced substitutions, Methods and functions
@c node-name, next, previous, up
@section Applying a function on subexpressions
@cindex tree traversal
@cindex @code{map()}
Sometimes you may want to perform an operation on specific parts of an
expression while leaving the general structure of it intact. An example
of this would be a matrix trace operation: the trace of a sum is the sum
of the traces of the individual terms. That is, the trace should @dfn{map}
on the sum, by applying itself to each of the sum's operands. It is possible
to do this manually which usually results in code like this:
@example
ex calc_trace(ex e)
@{
if (is_a<matrix>(e))
return ex_to<matrix>(e).trace();
else if (is_a<add>(e)) @{
ex sum = 0;
for (size_t i=0; i<e.nops(); i++)
sum += calc_trace(e.op(i));
return sum;
@} else if (is_a<mul>)(e)) @{
...
@} else @{
...
@}
@}
@end example
This is, however, slightly inefficient (if the sum is very large it can take
a long time to add the terms one-by-one), and its applicability is limited to
a rather small class of expressions. If @code{calc_trace()} is called with
a relation or a list as its argument, you will probably want the trace to
be taken on both sides of the relation or of all elements of the list.
GiNaC offers the @code{map()} method to aid in the implementation of such
operations:
@example
ex ex::map(map_function & f) const;
ex ex::map(ex (*f)(const ex & e)) const;
@end example
In the first (preferred) form, @code{map()} takes a function object that
is subclassed from the @code{map_function} class. In the second form, it
takes a pointer to a function that accepts and returns an expression.
@code{map()} constructs a new expression of the same type, applying the
specified function on all subexpressions (in the sense of @code{op()}),
non-recursively.
The use of a function object makes it possible to supply more arguments to
the function that is being mapped, or to keep local state information.
The @code{map_function} class declares a virtual function call operator
that you can overload. Here is a sample implementation of @code{calc_trace()}
that uses @code{map()} in a recursive fashion:
@example
struct calc_trace : public map_function @{
ex operator()(const ex &e)
@{
if (is_a<matrix>(e))
return ex_to<matrix>(e).trace();
else if (is_a<mul>(e)) @{
...
@} else
return e.map(*this);
@}
@};
@end example
This function object could then be used like this:
@example
@{
ex M = ... // expression with matrices
calc_trace do_trace;
ex tr = do_trace(M);
@}
@end example
Here is another example for you to meditate over. It removes quadratic
terms in a variable from an expanded polynomial:
@example
struct map_rem_quad : public map_function @{
ex var;
map_rem_quad(const ex & var_) : var(var_) @{@}
ex operator()(const ex & e)
@{
if (is_a<add>(e) || is_a<mul>(e))
return e.map(*this);
else if (is_a<power>(e) &&
e.op(0).is_equal(var) && e.op(1).info(info_flags::even))
return 0;
else
return e;
@}
@};
...
@{
symbol x("x"), y("y");
ex e;
for (int i=0; i<8; i++)
e += pow(x, i) * pow(y, 8-i) * (i+1);
cout << e << endl;
// -> 4*y^5*x^3+5*y^4*x^4+8*y*x^7+7*y^2*x^6+2*y^7*x+6*y^3*x^5+3*y^6*x^2+y^8
map_rem_quad rem_quad(x);
cout << rem_quad(e) << endl;
// -> 4*y^5*x^3+8*y*x^7+2*y^7*x+6*y^3*x^5+y^8
@}
@end example
@command{ginsh} offers a slightly different implementation of @code{map()}
that allows applying algebraic functions to operands. The second argument
to @code{map()} is an expression containing the wildcard @samp{$0} which
acts as the placeholder for the operands:
@example
> map(a*b,sin($0));
sin(a)*sin(b)
> map(a+2*b,sin($0));
sin(a)+sin(2*b)
> map(@{a,b,c@},$0^2+$0);
@{a^2+a,b^2+b,c^2+c@}
@end example
Note that it is only possible to use algebraic functions in the second
argument. You can not use functions like @samp{diff()}, @samp{op()},
@samp{subs()} etc. because these are evaluated immediately:
@example
> map(@{a,b,c@},diff($0,a));
@{0,0,0@}
This is because "diff($0,a)" evaluates to "0", so the command is equivalent
to "map(@{a,b,c@},0)".
@end example
@node Visitors and tree traversal, Polynomial arithmetic, Applying a function on subexpressions, Methods and functions
@c node-name, next, previous, up
@section Visitors and tree traversal
@cindex tree traversal
@cindex @code{visitor} (class)
@cindex @code{accept()}
@cindex @code{visit()}
@cindex @code{traverse()}
@cindex @code{traverse_preorder()}
@cindex @code{traverse_postorder()}
Suppose that you need a function that returns a list of all indices appearing
in an arbitrary expression. The indices can have any dimension, and for
indices with variance you always want the covariant version returned.
You can't use @code{get_free_indices()} because you also want to include
dummy indices in the list, and you can't use @code{find()} as it needs
specific index dimensions (and it would require two passes: one for indices
with variance, one for plain ones).
The obvious solution to this problem is a tree traversal with a type switch,
such as the following:
@example
void gather_indices_helper(const ex & e, lst & l)
@{
if (is_a<varidx>(e)) @{
const varidx & vi = ex_to<varidx>(e);
l.append(vi.is_covariant() ? vi : vi.toggle_variance());
@} else if (is_a<idx>(e)) @{
l.append(e);
@} else @{
size_t n = e.nops();
for (size_t i = 0; i < n; ++i)
gather_indices_helper(e.op(i), l);
@}
@}
lst gather_indices(const ex & e)
@{
lst l;
gather_indices_helper(e, l);
l.sort();
l.unique();
return l;
@}
@end example
This works fine but fans of object-oriented programming will feel
uncomfortable with the type switch. One reason is that there is a possibility
for subtle bugs regarding derived classes. If we had, for example, written
@example
if (is_a<idx>(e)) @{
...
@} else if (is_a<varidx>(e)) @{
...
@end example
in @code{gather_indices_helper}, the code wouldn't have worked because the
first line "absorbs" all classes derived from @code{idx}, including
@code{varidx}, so the special case for @code{varidx} would never have been
executed.
Also, for a large number of classes, a type switch like the above can get
unwieldy and inefficient (it's a linear search, after all).
@code{gather_indices_helper} only checks for two classes, but if you had to
write a function that required a different implementation for nearly
every GiNaC class, the result would be very hard to maintain and extend.
The cleanest approach to the problem would be to add a new virtual function
to GiNaC's class hierarchy. In our example, there would be specializations
for @code{idx} and @code{varidx} while the default implementation in
@code{basic} performed the tree traversal. Unfortunately, in C++ it's
impossible to add virtual member functions to existing classes without
changing their source and recompiling everything. GiNaC comes with source,
so you could actually do this, but for a small algorithm like the one
presented this would be impractical.
One solution to this dilemma is the @dfn{Visitor} design pattern,
which is implemented in GiNaC (actually, Robert Martin's Acyclic Visitor
variation, described in detail in
@uref{http://objectmentor.com/publications/acv.pdf}). Instead of adding
virtual functions to the class hierarchy to implement operations, GiNaC
provides a single "bouncing" method @code{accept()} that takes an instance
of a special @code{visitor} class and redirects execution to the one
@code{visit()} virtual function of the visitor that matches the type of
object that @code{accept()} was being invoked on.
Visitors in GiNaC must derive from the global @code{visitor} class as well
as from the class @code{T::visitor} of each class @code{T} they want to
visit, and implement the member functions @code{void visit(const T &)} for
each class.
A call of
@example
void ex::accept(visitor & v) const;
@end example
will then dispatch to the correct @code{visit()} member function of the
specified visitor @code{v} for the type of GiNaC object at the root of the
expression tree (e.g. a @code{symbol}, an @code{idx} or a @code{mul}).
Here is an example of a visitor:
@example
class my_visitor
: public visitor, // this is required
public add::visitor, // visit add objects
public numeric::visitor, // visit numeric objects
public basic::visitor // visit basic objects
@{
void visit(const add & x)
@{ cout << "called with an add object" << endl; @}
void visit(const numeric & x)
@{ cout << "called with a numeric object" << endl; @}
void visit(const basic & x)
@{ cout << "called with a basic object" << endl; @}
@};
@end example
which can be used as follows:
@example
...
symbol x("x");
ex e1 = 42;
ex e2 = 4*x-3;
ex e3 = 8*x;
my_visitor v;
e1.accept(v);
// prints "called with a numeric object"
e2.accept(v);
// prints "called with an add object"
e3.accept(v);
// prints "called with a basic object"
...
@end example
The @code{visit(const basic &)} method gets called for all objects that are
not @code{numeric} or @code{add} and acts as an (optional) default.
From a conceptual point of view, the @code{visit()} methods of the visitor
behave like a newly added virtual function of the visited hierarchy.
In addition, visitors can store state in member variables, and they can
be extended by deriving a new visitor from an existing one, thus building
hierarchies of visitors.
We can now rewrite our index example from above with a visitor:
@example
class gather_indices_visitor
: public visitor, public idx::visitor, public varidx::visitor
@{
lst l;
void visit(const idx & i)
@{
l.append(i);
@}
void visit(const varidx & vi)
@{
l.append(vi.is_covariant() ? vi : vi.toggle_variance());
@}
public:
const lst & get_result() // utility function
@{
l.sort();
l.unique();
return l;
@}
@};
@end example
What's missing is the tree traversal. We could implement it in
@code{visit(const basic &)}, but GiNaC has predefined methods for this:
@example
void ex::traverse_preorder(visitor & v) const;
void ex::traverse_postorder(visitor & v) const;
void ex::traverse(visitor & v) const;
@end example
@code{traverse_preorder()} visits a node @emph{before} visiting its
subexpressions, while @code{traverse_postorder()} visits a node @emph{after}
visiting its subexpressions. @code{traverse()} is a synonym for
@code{traverse_preorder()}.
Here is a new implementation of @code{gather_indices()} that uses the visitor
and @code{traverse()}:
@example
lst gather_indices(const ex & e)
@{
gather_indices_visitor v;
e.traverse(v);
return v.get_result();
@}
@end example
Alternatively, you could use pre- or postorder iterators for the tree
traversal:
@example
lst gather_indices(const ex & e)
@{
gather_indices_visitor v;
for (const_preorder_iterator i = e.preorder_begin();
i != e.preorder_end(); ++i) @{
i->accept(v);
@}
return v.get_result();
@}
@end example
@node Polynomial arithmetic, Rational expressions, Visitors and tree traversal, Methods and functions
@c node-name, next, previous, up
@section Polynomial arithmetic
@subsection Testing whether an expression is a polynomial
@cindex @code{is_polynomial()}
Testing whether an expression is a polynomial in one or more variables
can be done with the method
@example
bool ex::is_polynomial(const ex & vars) const;
@end example
In the case of more than
one variable, the variables are given as a list.
@example
(x*y*sin(y)).is_polynomial(x) // Returns true.
(x*y*sin(y)).is_polynomial(lst(x,y)) // Returns false.
@end example
@subsection Expanding and collecting
@cindex @code{expand()}
@cindex @code{collect()}
@cindex @code{collect_common_factors()}
A polynomial in one or more variables has many equivalent
representations. Some useful ones serve a specific purpose. Consider
for example the trivariate polynomial @math{4*x*y + x*z + 20*y^2 +
21*y*z + 4*z^2} (written down here in output-style). It is equivalent
to the factorized polynomial @math{(x + 5*y + 4*z)*(4*y + z)}. Other
representations are the recursive ones where one collects for exponents
in one of the three variable. Since the factors are themselves
polynomials in the remaining two variables the procedure can be
repeated. In our example, two possibilities would be @math{(4*y + z)*x
+ 20*y^2 + 21*y*z + 4*z^2} and @math{20*y^2 + (21*z + 4*x)*y + 4*z^2 +
x*z}.
To bring an expression into expanded form, its method
@example
ex ex::expand(unsigned options = 0);
@end example
may be called. In our example above, this corresponds to @math{4*x*y +
x*z + 20*y^2 + 21*y*z + 4*z^2}. Again, since the canonical form in
GiNaC is not easy to guess you should be prepared to see different
orderings of terms in such sums!
Another useful representation of multivariate polynomials is as a
univariate polynomial in one of the variables with the coefficients
being polynomials in the remaining variables. The method
@code{collect()} accomplishes this task:
@example
ex ex::collect(const ex & s, bool distributed = false);
@end example
The first argument to @code{collect()} can also be a list of objects in which
case the result is either a recursively collected polynomial, or a polynomial
in a distributed form with terms like @math{c*x1^e1*...*xn^en}, as specified
by the @code{distributed} flag.
Note that the original polynomial needs to be in expanded form (for the
variables concerned) in order for @code{collect()} to be able to find the
coefficients properly.
The following @command{ginsh} transcript shows an application of @code{collect()}
together with @code{find()}:
@example
> a=expand((sin(x)+sin(y))*(1+p+q)*(1+d));
d*p*sin(x)+p*sin(x)+q*d*sin(x)+q*sin(y)+d*sin(x)+q*d*sin(y)+sin(y)+d*sin(y)
+q*sin(x)+d*sin(y)*p+sin(x)+sin(y)*p
> collect(a,@{p,q@});
d*sin(x)+(d*sin(x)+sin(y)+d*sin(y)+sin(x))*p
+(d*sin(x)+sin(y)+d*sin(y)+sin(x))*q+sin(y)+d*sin(y)+sin(x)
> collect(a,find(a,sin($1)));
(1+q+d+q*d+d*p+p)*sin(y)+(1+q+d+q*d+d*p+p)*sin(x)
> collect(a,@{find(a,sin($1)),p,q@});
(1+(1+d)*p+d+q*(1+d))*sin(x)+(1+(1+d)*p+d+q*(1+d))*sin(y)
> collect(a,@{find(a,sin($1)),d@});
(1+q+d*(1+q+p)+p)*sin(y)+(1+q+d*(1+q+p)+p)*sin(x)
@end example
Polynomials can often be brought into a more compact form by collecting
common factors from the terms of sums. This is accomplished by the function
@example
ex collect_common_factors(const ex & e);
@end example
This function doesn't perform a full factorization but only looks for
factors which are already explicitly present:
@example
> collect_common_factors(a*x+a*y);
(x+y)*a
> collect_common_factors(a*x^2+2*a*x*y+a*y^2);
a*(2*x*y+y^2+x^2)
> collect_common_factors(a*(b*(a+c)*x+b*((a+c)*x+(a+c)*y)*y));
(c+a)*a*(x*y+y^2+x)*b
@end example
@subsection Degree and coefficients
@cindex @code{degree()}
@cindex @code{ldegree()}
@cindex @code{coeff()}
The degree and low degree of a polynomial can be obtained using the two
methods
@example
int ex::degree(const ex & s);
int ex::ldegree(const ex & s);
@end example
which also work reliably on non-expanded input polynomials (they even work
on rational functions, returning the asymptotic degree). By definition, the
degree of zero is zero. To extract a coefficient with a certain power from
an expanded polynomial you use
@example
ex ex::coeff(const ex & s, int n);
@end example
You can also obtain the leading and trailing coefficients with the methods
@example
ex ex::lcoeff(const ex & s);
ex ex::tcoeff(const ex & s);
@end example
which are equivalent to @code{coeff(s, degree(s))} and @code{coeff(s, ldegree(s))},
respectively.
An application is illustrated in the next example, where a multivariate
polynomial is analyzed:
@example
@{
symbol x("x"), y("y");
ex PolyInp = 4*pow(x,3)*y + 5*x*pow(y,2) + 3*y
- pow(x+y,2) + 2*pow(y+2,2) - 8;
ex Poly = PolyInp.expand();
for (int i=Poly.ldegree(x); i<=Poly.degree(x); ++i) @{
cout << "The x^" << i << "-coefficient is "
<< Poly.coeff(x,i) << endl;
@}
cout << "As polynomial in y: "
<< Poly.collect(y) << endl;
@}
@end example
When run, it returns an output in the following fashion:
@example
The x^0-coefficient is y^2+11*y
The x^1-coefficient is 5*y^2-2*y
The x^2-coefficient is -1
The x^3-coefficient is 4*y
As polynomial in y: -x^2+(5*x+1)*y^2+(-2*x+4*x^3+11)*y
@end example
As always, the exact output may vary between different versions of GiNaC
or even from run to run since the internal canonical ordering is not
within the user's sphere of influence.
@code{degree()}, @code{ldegree()}, @code{coeff()}, @code{lcoeff()},
@code{tcoeff()} and @code{collect()} can also be used to a certain degree
with non-polynomial expressions as they not only work with symbols but with
constants, functions and indexed objects as well:
@example
@{
symbol a("a"), b("b"), c("c"), x("x");
idx i(symbol("i"), 3);
ex e = pow(sin(x) - cos(x), 4);
cout << e.degree(cos(x)) << endl;
// -> 4
cout << e.expand().coeff(sin(x), 3) << endl;
// -> -4*cos(x)
e = indexed(a+b, i) * indexed(b+c, i);
e = e.expand(expand_options::expand_indexed);
cout << e.collect(indexed(b, i)) << endl;
// -> a.i*c.i+(a.i+c.i)*b.i+b.i^2
@}
@end example
@subsection Polynomial division
@cindex polynomial division
@cindex quotient
@cindex remainder
@cindex pseudo-remainder
@cindex @code{quo()}
@cindex @code{rem()}
@cindex @code{prem()}
@cindex @code{divide()}
The two functions
@example
ex quo(const ex & a, const ex & b, const ex & x);
ex rem(const ex & a, const ex & b, const ex & x);
@end example
compute the quotient and remainder of univariate polynomials in the variable
@samp{x}. The results satisfy @math{a = b*quo(a, b, x) + rem(a, b, x)}.
The additional function
@example
ex prem(const ex & a, const ex & b, const ex & x);
@end example
computes the pseudo-remainder of @samp{a} and @samp{b} which satisfies
@math{c*a = b*q + prem(a, b, x)}, where @math{c = b.lcoeff(x) ^ (a.degree(x) - b.degree(x) + 1)}.
Exact division of multivariate polynomials is performed by the function
@example
bool divide(const ex & a, const ex & b, ex & q);
@end example
If @samp{b} divides @samp{a} over the rationals, this function returns @code{true}
and returns the quotient in the variable @code{q}. Otherwise it returns @code{false}
in which case the value of @code{q} is undefined.
@subsection Unit, content and primitive part
@cindex @code{unit()}
@cindex @code{content()}
@cindex @code{primpart()}
@cindex @code{unitcontprim()}
The methods
@example
ex ex::unit(const ex & x);
ex ex::content(const ex & x);
ex ex::primpart(const ex & x);
ex ex::primpart(const ex & x, const ex & c);
@end example
return the unit part, content part, and primitive polynomial of a multivariate
polynomial with respect to the variable @samp{x} (the unit part being the sign
of the leading coefficient, the content part being the GCD of the coefficients,
and the primitive polynomial being the input polynomial divided by the unit and
content parts). The second variant of @code{primpart()} expects the previously
calculated content part of the polynomial in @code{c}, which enables it to
work faster in the case where the content part has already been computed. The
product of unit, content, and primitive part is the original polynomial.
Additionally, the method
@example
void ex::unitcontprim(const ex & x, ex & u, ex & c, ex & p);
@end example
computes the unit, content, and primitive parts in one go, returning them
in @code{u}, @code{c}, and @code{p}, respectively.
@subsection GCD, LCM and resultant
@cindex GCD
@cindex LCM
@cindex @code{gcd()}
@cindex @code{lcm()}
The functions for polynomial greatest common divisor and least common
multiple have the synopsis
@example
ex gcd(const ex & a, const ex & b);
ex lcm(const ex & a, const ex & b);
@end example
The functions @code{gcd()} and @code{lcm()} accept two expressions
@code{a} and @code{b} as arguments and return a new expression, their
greatest common divisor or least common multiple, respectively. If the
polynomials @code{a} and @code{b} are coprime @code{gcd(a,b)} returns 1
and @code{lcm(a,b)} returns the product of @code{a} and @code{b}. Note that all
the coefficients must be rationals.
@example
#include <ginac/ginac.h>
using namespace GiNaC;
int main()
@{
symbol x("x"), y("y"), z("z");
ex P_a = 4*x*y + x*z + 20*pow(y, 2) + 21*y*z + 4*pow(z, 2);
ex P_b = x*y + 3*x*z + 5*pow(y, 2) + 19*y*z + 12*pow(z, 2);
ex P_gcd = gcd(P_a, P_b);
// x + 5*y + 4*z
ex P_lcm = lcm(P_a, P_b);
// 4*x*y^2 + 13*y*x*z + 20*y^3 + 81*y^2*z + 67*y*z^2 + 3*x*z^2 + 12*z^3
@}
@end example
@cindex resultant
@cindex @code{resultant()}
The resultant of two expressions only makes sense with polynomials.
It is always computed with respect to a specific symbol within the
expressions. The function has the interface
@example
ex resultant(const ex & a, const ex & b, const ex & s);
@end example
Resultants are symmetric in @code{a} and @code{b}. The following example
computes the resultant of two expressions with respect to @code{x} and
@code{y}, respectively:
@example
#include <ginac/ginac.h>
using namespace GiNaC;
int main()
@{
symbol x("x"), y("y");
ex e1 = x+pow(y,2), e2 = 2*pow(x,3)-1; // x+y^2, 2*x^3-1
ex r;
r = resultant(e1, e2, x);
// -> 1+2*y^6
r = resultant(e1, e2, y);
// -> 1-4*x^3+4*x^6
@}
@end example
@subsection Square-free decomposition
@cindex square-free decomposition
@cindex factorization
@cindex @code{sqrfree()}
Square-free decomposition is available in GiNaC:
@example
ex sqrfree(const ex & a, const lst & l = lst());
@end example
Here is an example that by the way illustrates how the exact form of the
result may slightly depend on the order of differentiation, calling for
some care with subsequent processing of the result:
@example
...
symbol x("x"), y("y");
ex BiVarPol = expand(pow(2-2*y,3) * pow(1+x*y,2) * pow(x-2*y,2) * (x+y));
cout << sqrfree(BiVarPol, lst(x,y)) << endl;
// -> 8*(1-y)^3*(y*x^2-2*y+x*(1-2*y^2))^2*(y+x)
cout << sqrfree(BiVarPol, lst(y,x)) << endl;
// -> 8*(1-y)^3*(-y*x^2+2*y+x*(-1+2*y^2))^2*(y+x)
cout << sqrfree(BiVarPol) << endl;
// -> depending on luck, any of the above
...
@end example
Note also, how factors with the same exponents are not fully factorized
with this method.
@subsection Polynomial factorization
@cindex factorization
@cindex polynomial factorization
@cindex @code{factor()}
Polynomials can also be fully factored with a call to the function
@example
ex factor(const ex & a, unsigned int options = 0);
@end example
The factorization works for univariate and multivariate polynomials with
rational coefficients. The following code snippet shows its capabilities:
@example
...
cout << factor(pow(x,2)-1) << endl;
// -> (1+x)*(-1+x)
cout << factor(expand((x-y*z)*(x-pow(y,2)-pow(z,3))*(x+y+z))) << endl;
// -> (y+z+x)*(y*z-x)*(y^2-x+z^3)
cout << factor(pow(x,2)-1+sin(pow(x,2)-1)) << endl;
// -> -1+sin(-1+x^2)+x^2
...
@end example
The results are as expected except for the last one where no factorization
seems to have been done. This is due to the default option
@command{factor_options::polynomial} (equals zero) to @command{factor()}, which
tells GiNaC to try a factorization only if the expression is a valid polynomial.
In the shown example this is not the case, because one term is a function.
There exists a second option @command{factor_options::all}, which tells GiNaC to
ignore non-polynomial parts of an expression and also to look inside function
arguments. With this option the example gives:
@example
...
cout << factor(pow(x,2)-1+sin(pow(x,2)-1), factor_options::all)
<< endl;
// -> (-1+x)*(1+x)+sin((-1+x)*(1+x))
...
@end example
GiNaC's factorization functions cannot handle algebraic extensions. Therefore
the following example does not factor:
@example
...
cout << factor(pow(x,2)-2) << endl;
// -> -2+x^2 and not (x-sqrt(2))*(x+sqrt(2))
...
@end example
Factorization is useful in many applications. A lot of algorithms in computer
algebra depend on the ability to factor a polynomial. Of course, factorization
can also be used to simplify expressions, but it is costly and applying it to
complicated expressions (high degrees or many terms) may consume far too much
time. So usually, looking for a GCD at strategic points in a calculation is the
cheaper and more appropriate alternative.
@node Rational expressions, Symbolic differentiation, Polynomial arithmetic, Methods and functions
@c node-name, next, previous, up
@section Rational expressions
@subsection The @code{normal} method
@cindex @code{normal()}
@cindex simplification
@cindex temporary replacement
Some basic form of simplification of expressions is called for frequently.
GiNaC provides the method @code{.normal()}, which converts a rational function
into an equivalent rational function of the form @samp{numerator/denominator}
where numerator and denominator are coprime. If the input expression is already
a fraction, it just finds the GCD of numerator and denominator and cancels it,
otherwise it performs fraction addition and multiplication.
@code{.normal()} can also be used on expressions which are not rational functions
as it will replace all non-rational objects (like functions or non-integer
powers) by temporary symbols to bring the expression to the domain of rational
functions before performing the normalization, and re-substituting these
symbols afterwards. This algorithm is also available as a separate method
@code{.to_rational()}, described below.
This means that both expressions @code{t1} and @code{t2} are indeed
simplified in this little code snippet:
@example
@{
symbol x("x");
ex t1 = (pow(x,2) + 2*x + 1)/(x + 1);
ex t2 = (pow(sin(x),2) + 2*sin(x) + 1)/(sin(x) + 1);
std::cout << "t1 is " << t1.normal() << std::endl;
std::cout << "t2 is " << t2.normal() << std::endl;
@}
@end example
Of course this works for multivariate polynomials too, so the ratio of
the sample-polynomials from the section about GCD and LCM above would be
normalized to @code{P_a/P_b} = @code{(4*y+z)/(y+3*z)}.
@subsection Numerator and denominator
@cindex numerator
@cindex denominator
@cindex @code{numer()}
@cindex @code{denom()}
@cindex @code{numer_denom()}
The numerator and denominator of an expression can be obtained with
@example
ex ex::numer();
ex ex::denom();
ex ex::numer_denom();
@end example
These functions will first normalize the expression as described above and
then return the numerator, denominator, or both as a list, respectively.
If you need both numerator and denominator, calling @code{numer_denom()} is
faster than using @code{numer()} and @code{denom()} separately.
@subsection Converting to a polynomial or rational expression
@cindex @code{to_polynomial()}
@cindex @code{to_rational()}
Some of the methods described so far only work on polynomials or rational
functions. GiNaC provides a way to extend the domain of these functions to
general expressions by using the temporary replacement algorithm described
above. You do this by calling
@example
ex ex::to_polynomial(exmap & m);
ex ex::to_polynomial(lst & l);
@end example
or
@example
ex ex::to_rational(exmap & m);
ex ex::to_rational(lst & l);
@end example
on the expression to be converted. The supplied @code{exmap} or @code{lst}
will be filled with the generated temporary symbols and their replacement
expressions in a format that can be used directly for the @code{subs()}
method. It can also already contain a list of replacements from an earlier
application of @code{.to_polynomial()} or @code{.to_rational()}, so it's
possible to use it on multiple expressions and get consistent results.
The difference between @code{.to_polynomial()} and @code{.to_rational()}
is probably best illustrated with an example:
@example
@{
symbol x("x"), y("y");
ex a = 2*x/sin(x) - y/(3*sin(x));
cout << a << endl;
lst lp;
ex p = a.to_polynomial(lp);
cout << " = " << p << "\n with " << lp << endl;
// = symbol3*symbol2*y+2*symbol2*x
// with @{symbol2==sin(x)^(-1),symbol3==-1/3@}
lst lr;
ex r = a.to_rational(lr);
cout << " = " << r << "\n with " << lr << endl;
// = -1/3*symbol4^(-1)*y+2*symbol4^(-1)*x
// with @{symbol4==sin(x)@}
@}
@end example
The following more useful example will print @samp{sin(x)-cos(x)}:
@example
@{
symbol x("x");
ex a = pow(sin(x), 2) - pow(cos(x), 2);
ex b = sin(x) + cos(x);
ex q;
exmap m;
divide(a.to_polynomial(m), b.to_polynomial(m), q);
cout << q.subs(m) << endl;
@}
@end example
@node Symbolic differentiation, Series expansion, Rational expressions, Methods and functions
@c node-name, next, previous, up
@section Symbolic differentiation
@cindex differentiation
@cindex @code{diff()}
@cindex chain rule
@cindex product rule
GiNaC's objects know how to differentiate themselves. Thus, a
polynomial (class @code{add}) knows that its derivative is the sum of
the derivatives of all the monomials:
@example
@{
symbol x("x"), y("y"), z("z");
ex P = pow(x, 5) + pow(x, 2) + y;
cout << P.diff(x,2) << endl;
// -> 20*x^3 + 2
cout << P.diff(y) << endl; // 1
// -> 1
cout << P.diff(z) << endl; // 0
// -> 0
@}
@end example
If a second integer parameter @var{n} is given, the @code{diff} method
returns the @var{n}th derivative.
If @emph{every} object and every function is told what its derivative
is, all derivatives of composed objects can be calculated using the
chain rule and the product rule. Consider, for instance the expression
@code{1/cosh(x)}. Since the derivative of @code{cosh(x)} is
@code{sinh(x)} and the derivative of @code{pow(x,-1)} is
@code{-pow(x,-2)}, GiNaC can readily compute the composition. It turns
out that the composition is the generating function for Euler Numbers,
i.e. the so called @var{n}th Euler number is the coefficient of
@code{x^n/n!} in the expansion of @code{1/cosh(x)}. We may use this
identity to code a function that generates Euler numbers in just three
lines:
@cindex Euler numbers
@example
#include <ginac/ginac.h>
using namespace GiNaC;
ex EulerNumber(unsigned n)
@{
symbol x;
const ex generator = pow(cosh(x),-1);
return generator.diff(x,n).subs(x==0);
@}
int main()
@{
for (unsigned i=0; i<11; i+=2)
std::cout << EulerNumber(i) << std::endl;
return 0;
@}
@end example
When you run it, it produces the sequence @code{1}, @code{-1}, @code{5},
@code{-61}, @code{1385}, @code{-50521}. We increment the loop variable
@code{i} by two since all odd Euler numbers vanish anyways.
@node Series expansion, Symmetrization, Symbolic differentiation, Methods and functions
@c node-name, next, previous, up
@section Series expansion
@cindex @code{series()}
@cindex Taylor expansion
@cindex Laurent expansion
@cindex @code{pseries} (class)
@cindex @code{Order()}
Expressions know how to expand themselves as a Taylor series or (more
generally) a Laurent series. As in most conventional Computer Algebra
Systems, no distinction is made between those two. There is a class of
its own for storing such series (@code{class pseries}) and a built-in
function (called @code{Order}) for storing the order term of the series.
As a consequence, if you want to work with series, i.e. multiply two
series, you need to call the method @code{ex::series} again to convert
it to a series object with the usual structure (expansion plus order
term). A sample application from special relativity could read:
@example
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
int main()
@{
symbol v("v"), c("c");
ex gamma = 1/sqrt(1 - pow(v/c,2));
ex mass_nonrel = gamma.series(v==0, 10);
cout << "the relativistic mass increase with v is " << endl
<< mass_nonrel << endl;
cout << "the inverse square of this series is " << endl
<< pow(mass_nonrel,-2).series(v==0, 10) << endl;
@}
@end example
Only calling the series method makes the last output simplify to
@math{1-v^2/c^2+O(v^10)}, without that call we would just have a long
series raised to the power @math{-2}.
@cindex Machin's formula
As another instructive application, let us calculate the numerical
value of Archimedes' constant
@tex
$\pi$
@end tex
@ifnottex
@math{Pi}
@end ifnottex
(for which there already exists the built-in constant @code{Pi})
using John Machin's amazing formula
@tex
$\pi=16$~atan~$\!\left(1 \over 5 \right)-4$~atan~$\!\left(1 \over 239 \right)$.
@end tex
@ifnottex
@math{Pi==16*atan(1/5)-4*atan(1/239)}.
@end ifnottex
This equation (and similar ones) were used for over 200 years for
computing digits of pi (see @cite{Pi Unleashed}). We may expand the
arcus tangent around @code{0} and insert the fractions @code{1/5} and
@code{1/239}. However, as we have seen, a series in GiNaC carries an
order term with it and the question arises what the system is supposed
to do when the fractions are plugged into that order term. The solution
is to use the function @code{series_to_poly()} to simply strip the order
term off:
@example
#include <ginac/ginac.h>
using namespace GiNaC;
ex machin_pi(int degr)
@{
symbol x;
ex pi_expansion = series_to_poly(atan(x).series(x,degr));
ex pi_approx = 16*pi_expansion.subs(x==numeric(1,5))
-4*pi_expansion.subs(x==numeric(1,239));
return pi_approx;
@}
int main()
@{
using std::cout; // just for fun, another way of...
using std::endl; // ...dealing with this namespace std.
ex pi_frac;
for (int i=2; i<12; i+=2) @{
pi_frac = machin_pi(i);
cout << i << ":\t" << pi_frac << endl
<< "\t" << pi_frac.evalf() << endl;
@}
return 0;
@}
@end example
Note how we just called @code{.series(x,degr)} instead of
@code{.series(x==0,degr)}. This is a simple shortcut for @code{ex}'s
method @code{series()}: if the first argument is a symbol the expression
is expanded in that symbol around point @code{0}. When you run this
program, it will type out:
@example
2: 3804/1195
3.1832635983263598326
4: 5359397032/1706489875
3.1405970293260603143
6: 38279241713339684/12184551018734375
3.141621029325034425
8: 76528487109180192540976/24359780855939418203125
3.141591772182177295
10: 327853873402258685803048818236/104359128170408663038552734375
3.1415926824043995174
@end example
@node Symmetrization, Built-in functions, Series expansion, Methods and functions
@c node-name, next, previous, up
@section Symmetrization
@cindex @code{symmetrize()}
@cindex @code{antisymmetrize()}
@cindex @code{symmetrize_cyclic()}
The three methods
@example
ex ex::symmetrize(const lst & l);
ex ex::antisymmetrize(const lst & l);
ex ex::symmetrize_cyclic(const lst & l);
@end example
symmetrize an expression by returning the sum over all symmetric,
antisymmetric or cyclic permutations of the specified list of objects,
weighted by the number of permutations.
The three additional methods
@example
ex ex::symmetrize();
ex ex::antisymmetrize();
ex ex::symmetrize_cyclic();
@end example
symmetrize or antisymmetrize an expression over its free indices.
Symmetrization is most useful with indexed expressions but can be used with
almost any kind of object (anything that is @code{subs()}able):
@example
@{
idx i(symbol("i"), 3), j(symbol("j"), 3), k(symbol("k"), 3);
symbol A("A"), B("B"), a("a"), b("b"), c("c");
cout << indexed(A, i, j).symmetrize() << endl;
// -> 1/2*A.j.i+1/2*A.i.j
cout << indexed(A, i, j, k).antisymmetrize(lst(i, j)) << endl;
// -> -1/2*A.j.i.k+1/2*A.i.j.k
cout << lst(a, b, c).symmetrize_cyclic(lst(a, b, c)) << endl;
// -> 1/3*@{a,b,c@}+1/3*@{b,c,a@}+1/3*@{c,a,b@}
@}
@end example
@page
@node Built-in functions, Multiple polylogarithms, Symmetrization, Methods and functions
@c node-name, next, previous, up
@section Predefined mathematical functions
@c
@subsection Overview
GiNaC contains the following predefined mathematical functions:
@cartouche
@multitable @columnfractions .30 .70
@item @strong{Name} @tab @strong{Function}
@item @code{abs(x)}
@tab absolute value
@cindex @code{abs()}
@item @code{step(x)}
@tab step function
@cindex @code{step()}
@item @code{csgn(x)}
@tab complex sign
@cindex @code{conjugate()}
@item @code{conjugate(x)}
@tab complex conjugation
@cindex @code{real_part()}
@item @code{real_part(x)}
@tab real part
@cindex @code{imag_part()}
@item @code{imag_part(x)}
@tab imaginary part
@item @code{sqrt(x)}
@tab square root (not a GiNaC function, rather an alias for @code{pow(x, numeric(1, 2))})
@cindex @code{sqrt()}
@item @code{sin(x)}
@tab sine
@cindex @code{sin()}
@item @code{cos(x)}
@tab cosine
@cindex @code{cos()}
@item @code{tan(x)}
@tab tangent
@cindex @code{tan()}
@item @code{asin(x)}
@tab inverse sine
@cindex @code{asin()}
@item @code{acos(x)}
@tab inverse cosine
@cindex @code{acos()}
@item @code{atan(x)}
@tab inverse tangent
@cindex @code{atan()}
@item @code{atan2(y, x)}
@tab inverse tangent with two arguments
@item @code{sinh(x)}
@tab hyperbolic sine
@cindex @code{sinh()}
@item @code{cosh(x)}
@tab hyperbolic cosine
@cindex @code{cosh()}
@item @code{tanh(x)}
@tab hyperbolic tangent
@cindex @code{tanh()}
@item @code{asinh(x)}
@tab inverse hyperbolic sine
@cindex @code{asinh()}
@item @code{acosh(x)}
@tab inverse hyperbolic cosine
@cindex @code{acosh()}
@item @code{atanh(x)}
@tab inverse hyperbolic tangent
@cindex @code{atanh()}
@item @code{exp(x)}
@tab exponential function
@cindex @code{exp()}
@item @code{log(x)}
@tab natural logarithm
@cindex @code{log()}
@item @code{Li2(x)}
@tab dilogarithm
@cindex @code{Li2()}
@item @code{Li(m, x)}
@tab classical polylogarithm as well as multiple polylogarithm
@cindex @code{Li()}
@item @code{G(a, y)}
@tab multiple polylogarithm
@cindex @code{G()}
@item @code{G(a, s, y)}
@tab multiple polylogarithm with explicit signs for the imaginary parts
@cindex @code{G()}
@item @code{S(n, p, x)}
@tab Nielsen's generalized polylogarithm
@cindex @code{S()}
@item @code{H(m, x)}
@tab harmonic polylogarithm
@cindex @code{H()}
@item @code{zeta(m)}
@tab Riemann's zeta function as well as multiple zeta value
@cindex @code{zeta()}
@item @code{zeta(m, s)}
@tab alternating Euler sum
@cindex @code{zeta()}
@item @code{zetaderiv(n, x)}
@tab derivatives of Riemann's zeta function
@item @code{tgamma(x)}
@tab gamma function
@cindex @code{tgamma()}
@cindex gamma function
@item @code{lgamma(x)}
@tab logarithm of gamma function
@cindex @code{lgamma()}
@item @code{beta(x, y)}
@tab beta function (@code{tgamma(x)*tgamma(y)/tgamma(x+y)})
@cindex @code{beta()}
@item @code{psi(x)}
@tab psi (digamma) function
@cindex @code{psi()}
@item @code{psi(n, x)}
@tab derivatives of psi function (polygamma functions)
@item @code{factorial(n)}
@tab factorial function @math{n!}
@cindex @code{factorial()}
@item @code{binomial(n, k)}
@tab binomial coefficients
@cindex @code{binomial()}
@item @code{Order(x)}
@tab order term function in truncated power series
@cindex @code{Order()}
@end multitable
@end cartouche
@cindex branch cut
For functions that have a branch cut in the complex plane GiNaC follows
the conventions for C++ as defined in the ANSI standard as far as
possible. In particular: the natural logarithm (@code{log}) and the
square root (@code{sqrt}) both have their branch cuts running along the
negative real axis where the points on the axis itself belong to the
upper part (i.e. continuous with quadrant II). The inverse
trigonometric and hyperbolic functions are not defined for complex
arguments by the C++ standard, however. In GiNaC we follow the
conventions used by CLN, which in turn follow the carefully designed
definitions in the Common Lisp standard. It should be noted that this
convention is identical to the one used by the C99 standard and by most
serious CAS. It is to be expected that future revisions of the C++
standard incorporate these functions in the complex domain in a manner
compatible with C99.
@node Multiple polylogarithms, Complex expressions, Built-in functions, Methods and functions
@c node-name, next, previous, up
@subsection Multiple polylogarithms
@cindex polylogarithm
@cindex Nielsen's generalized polylogarithm
@cindex harmonic polylogarithm
@cindex multiple zeta value
@cindex alternating Euler sum
@cindex multiple polylogarithm
The multiple polylogarithm is the most generic member of a family of functions,
to which others like the harmonic polylogarithm, Nielsen's generalized
polylogarithm and the multiple zeta value belong.
Everyone of these functions can also be written as a multiple polylogarithm with specific
parameters. This whole family of functions is therefore often referred to simply as
multiple polylogarithms, containing @code{Li}, @code{G}, @code{H}, @code{S} and @code{zeta}.
The multiple polylogarithm itself comes in two variants: @code{Li} and @code{G}. While
@code{Li} and @code{G} in principle represent the same function, the different
notations are more natural to the series representation or the integral
representation, respectively.
To facilitate the discussion of these functions we distinguish between indices and
arguments as parameters. In the table above indices are printed as @code{m}, @code{s},
@code{n} or @code{p}, whereas arguments are printed as @code{x}, @code{a} and @code{y}.
To define a @code{Li}, @code{H} or @code{zeta} with a depth greater than one, you have to
pass a GiNaC @code{lst} for the indices @code{m} and @code{s}, and in the case of @code{Li}
for the argument @code{x} as well. The parameter @code{a} of @code{G} must always be a @code{lst} containing
the arguments in expanded form. If @code{G} is used with a third parameter @code{s}, @code{s} must
have the same length as @code{a}. It contains then the signs of the imaginary parts of the arguments. If
@code{s} is not given, the signs default to +1.
Note that @code{Li} and @code{zeta} are polymorphic in this respect. They can stand in for
the classical polylogarithm and Riemann's zeta function (if depth is one), as well as for
the multiple polylogarithm and the multiple zeta value, respectively. Note also, that
GiNaC doesn't check whether the @code{lst}s for two parameters do have the same length.
It is up to the user to ensure this, otherwise evaluating will result in undefined behavior.
The functions print in LaTeX format as
@tex
${\rm Li\;\!}_{m_1,m_2,\ldots,m_k}(x_1,x_2,\ldots,x_k)$,
@end tex
@tex
${\rm S}_{n,p}(x)$,
@end tex
@tex
${\rm H\;\!}_{m_1,m_2,\ldots,m_k}(x)$ and
@end tex
@tex
$\zeta(m_1,m_2,\ldots,m_k)$.
@end tex
@ifnottex
@command{\mbox@{Li@}_@{m_1,m_2,...,m_k@}(x_1,x_2,...,x_k)},
@command{\mbox@{S@}_@{n,p@}(x)},
@command{\mbox@{H@}_@{m_1,m_2,...,m_k@}(x)} and
@command{\zeta(m_1,m_2,...,m_k)} (with the dots replaced by actual parameters).
@end ifnottex
If @code{zeta} is an alternating zeta sum, i.e. @code{zeta(m,s)}, the indices with negative sign
are printed with a line above, e.g.
@tex
$\zeta(5,\overline{2})$.
@end tex
@ifnottex
@command{\zeta(5,\overline@{2@})}.
@end ifnottex
The order of indices and arguments in the GiNaC @code{lst}s and in the output is the same.
Definitions and analytical as well as numerical properties of multiple polylogarithms
are too numerous to be covered here. Instead, the user is referred to the publications listed at the
end of this section. The implementation in GiNaC adheres to the definitions and conventions therein,
except for a few differences which will be explicitly stated in the following.
One difference is about the order of the indices and arguments. For GiNaC we adopt the convention
that the indices and arguments are understood to be in the same order as in which they appear in
the series representation. This means
@tex
${\rm Li\;\!}_{m_1,m_2,m_3}(x,1,1) = {\rm H\;\!}_{m_1,m_2,m_3}(x)$ and
@end tex
@tex
${\rm Li\;\!}_{2,1}(1,1) = \zeta(2,1) = \zeta(3)$, but
@end tex
@tex
$\zeta(1,2)$ evaluates to infinity.
@end tex
@ifnottex
@code{Li_@{m_1,m_2,m_3@}(x,1,1) = H_@{m_1,m_2,m_3@}(x)} and
@code{Li_@{2,1@}(1,1) = zeta(2,1) = zeta(3)}, but
@code{zeta(1,2)} evaluates to infinity.
@end ifnottex
So in comparison to the older ones of the referenced publications the order of
indices and arguments for @code{Li} is reversed.
The functions only evaluate if the indices are integers greater than zero, except for the indices
@code{s} in @code{zeta} and @code{G} as well as @code{m} in @code{H}. Since @code{s}
will be interpreted as the sequence of signs for the corresponding indices
@code{m} or the sign of the imaginary part for the
corresponding arguments @code{a}, it must contain 1 or -1, e.g.
@code{zeta(lst(3,4), lst(-1,1))} means
@tex
$\zeta(\overline{3},4)$
@end tex
@ifnottex
@command{zeta(\overline@{3@},4)}
@end ifnottex
and
@code{G(lst(a,b), lst(-1,1), c)} means
@tex
$G(a-0\epsilon,b+0\epsilon;c)$.
@end tex
@ifnottex
@command{G(a-0\epsilon,b+0\epsilon;c)}.
@end ifnottex
The definition of @code{H} allows indices to be 0, 1 or -1 (in expanded notation) or equally to
be any integer (in compact notation). With GiNaC expanded and compact notation can be mixed,
e.g. @code{lst(0,0,-1,0,1,0,0)}, @code{lst(0,0,-1,2,0,0)} and @code{lst(-3,2,0,0)} are equivalent as
indices. The anonymous evaluator @code{eval()} tries to reduce the functions, if possible, to
the least-generic multiple polylogarithm. If all arguments are unit, it returns @code{zeta}.
Arguments equal to zero get considered, too. Riemann's zeta function @code{zeta} (with depth one)
evaluates also for negative integers and positive even integers. For example:
@example
> Li(@{3,1@},@{x,1@});
S(2,2,x)
> H(@{-3,2@},1);
-zeta(@{3,2@},@{-1,-1@})
> S(3,1,1);
1/90*Pi^4
@end example
It is easy to tell for a given function into which other function it can be rewritten, may
it be a less-generic or a more-generic one, except for harmonic polylogarithms @code{H}
with negative indices or trailing zeros (the example above gives a hint). Signs can
quickly be messed up, for example. Therefore GiNaC offers a C++ function
@code{convert_H_to_Li()} to deal with the upgrade of a @code{H} to a multiple polylogarithm
@code{Li} (@code{eval()} already cares for the possible downgrade):
@example
> convert_H_to_Li(@{0,-2,-1,3@},x);
Li(@{3,1,3@},@{-x,1,-1@})
> convert_H_to_Li(@{2,-1,0@},x);
-Li(@{2,1@},@{x,-1@})*log(x)+2*Li(@{3,1@},@{x,-1@})+Li(@{2,2@},@{x,-1@})
@end example
Every function can be numerically evaluated for
arbitrary real or complex arguments. The precision is arbitrary and can be set through the
global variable @code{Digits}:
@example
> Digits=100;
100
> evalf(zeta(@{3,1,3,1@}));
0.005229569563530960100930652283899231589890420784634635522547448972148869544...
@end example
Note that the convention for arguments on the branch cut in GiNaC as stated above is
different from the one Remiddi and Vermaseren have chosen for the harmonic polylogarithm.
If a function evaluates to infinity, no exceptions are raised, but the function is returned
unevaluated, e.g.
@tex
$\zeta(1)$.
@end tex
@ifnottex
@command{zeta(1)}.
@end ifnottex
In long expressions this helps a lot with debugging, because you can easily spot
the divergencies. But on the other hand, you have to make sure for yourself, that no illegal
cancellations of divergencies happen.
Useful publications:
@cite{Nested Sums, Expansion of Transcendental Functions and Multi-Scale Multi-Loop Integrals},
S.Moch, P.Uwer, S.Weinzierl, hep-ph/0110083
@cite{Harmonic Polylogarithms},
E.Remiddi, J.A.M.Vermaseren, Int.J.Mod.Phys. A15 (2000), pp. 725-754
@cite{Special Values of Multiple Polylogarithms},
J.Borwein, D.Bradley, D.Broadhurst, P.Lisonek, Trans.Amer.Math.Soc. 353/3 (2001), pp. 907-941
@cite{Numerical Evaluation of Multiple Polylogarithms},
J.Vollinga, S.Weinzierl, hep-ph/0410259
@node Complex expressions, Solving linear systems of equations, Multiple polylogarithms, Methods and functions
@c node-name, next, previous, up
@section Complex expressions
@c
@cindex @code{conjugate()}
For dealing with complex expressions there are the methods
@example
ex ex::conjugate();
ex ex::real_part();
ex ex::imag_part();
@end example
that return respectively the complex conjugate, the real part and the
imaginary part of an expression. Complex conjugation works as expected
for all built-in functions and objects. Taking real and imaginary
parts has not yet been implemented for all built-in functions. In cases where
it is not known how to conjugate or take a real/imaginary part one
of the functions @code{conjugate}, @code{real_part} or @code{imag_part}
is returned. For instance, in case of a complex symbol @code{x}
(symbols are complex by default), one could not simplify
@code{conjugate(x)}. In the case of strings of gamma matrices,
the @code{conjugate} method takes the Dirac conjugate.
For example,
@example
@{
varidx a(symbol("a"), 4), b(symbol("b"), 4);
symbol x("x");
realsymbol y("y");
cout << (3*I*x*y + sin(2*Pi*I*y)).conjugate() << endl;
// -> -3*I*conjugate(x)*y+sin(-2*I*Pi*y)
cout << (dirac_gamma(a)*dirac_gamma(b)*dirac_gamma5()).conjugate() << endl;
// -> -gamma5*gamma~b*gamma~a
@}
@end example
If you declare your own GiNaC functions and you want to conjugate them, you
will have to supply a specialized conjugation method for them (see
@ref{Symbolic functions} and the GiNaC source-code for @code{abs} as an
example). GiNaC does not automatically conjugate user-supplied functions
by conjugating their arguments because this would be incorrect on branch
cuts. Also, specialized methods can be provided to take real and imaginary
parts of user-defined functions.
@node Solving linear systems of equations, Input/output, Complex expressions, Methods and functions
@c node-name, next, previous, up
@section Solving linear systems of equations
@cindex @code{lsolve()}
The function @code{lsolve()} provides a convenient wrapper around some
matrix operations that comes in handy when a system of linear equations
needs to be solved:
@example
ex lsolve(const ex & eqns, const ex & symbols,
unsigned options = solve_algo::automatic);
@end example
Here, @code{eqns} is a @code{lst} of equalities (i.e. class
@code{relational}) while @code{symbols} is a @code{lst} of
indeterminates. (@xref{The class hierarchy}, for an exposition of class
@code{lst}).
It returns the @code{lst} of solutions as an expression. As an example,
let us solve the two equations @code{a*x+b*y==3} and @code{x-y==b}:
@example
@{
symbol a("a"), b("b"), x("x"), y("y");
lst eqns, vars;
eqns = a*x+b*y==3, x-y==b;
vars = x, y;
cout << lsolve(eqns, vars) << endl;
// -> @{x==(3+b^2)/(b+a),y==(3-b*a)/(b+a)@}
@end example
When the linear equations @code{eqns} are underdetermined, the solution
will contain one or more tautological entries like @code{x==x},
depending on the rank of the system. When they are overdetermined, the
solution will be an empty @code{lst}. Note the third optional parameter
to @code{lsolve()}: it accepts the same parameters as
@code{matrix::solve()}. This is because @code{lsolve} is just a wrapper
around that method.
@node Input/output, Extending GiNaC, Solving linear systems of equations, Methods and functions
@c node-name, next, previous, up
@section Input and output of expressions
@cindex I/O
@subsection Expression output
@cindex printing
@cindex output of expressions
Expressions can simply be written to any stream:
@example
@{
symbol x("x");
ex e = 4.5*I+pow(x,2)*3/2;
cout << e << endl; // prints '4.5*I+3/2*x^2'
// ...
@end example
The default output format is identical to the @command{ginsh} input syntax and
to that used by most computer algebra systems, but not directly pastable
into a GiNaC C++ program (note that in the above example, @code{pow(x,2)}
is printed as @samp{x^2}).
It is possible to print expressions in a number of different formats with
a set of stream manipulators;
@example
std::ostream & dflt(std::ostream & os);
std::ostream & latex(std::ostream & os);
std::ostream & tree(std::ostream & os);
std::ostream & csrc(std::ostream & os);
std::ostream & csrc_float(std::ostream & os);
std::ostream & csrc_double(std::ostream & os);
std::ostream & csrc_cl_N(std::ostream & os);
std::ostream & index_dimensions(std::ostream & os);
std::ostream & no_index_dimensions(std::ostream & os);
@end example
The @code{tree}, @code{latex} and @code{csrc} formats are also available in
@command{ginsh} via the @code{print()}, @code{print_latex()} and
@code{print_csrc()} functions, respectively.
@cindex @code{dflt}
All manipulators affect the stream state permanently. To reset the output
format to the default, use the @code{dflt} manipulator:
@example
// ...
cout << latex; // all output to cout will be in LaTeX format from
// now on
cout << e << endl; // prints '4.5 i+\frac@{3@}@{2@} x^@{2@}'
cout << sin(x/2) << endl; // prints '\sin(\frac@{1@}@{2@} x)'
cout << dflt; // revert to default output format
cout << e << endl; // prints '4.5*I+3/2*x^2'
// ...
@end example
If you don't want to affect the format of the stream you're working with,
you can output to a temporary @code{ostringstream} like this:
@example
// ...
ostringstream s;
s << latex << e; // format of cout remains unchanged
cout << s.str() << endl; // prints '4.5 i+\frac@{3@}@{2@} x^@{2@}'
// ...
@end example
@anchor{csrc printing}
@cindex @code{csrc}
@cindex @code{csrc_float}
@cindex @code{csrc_double}
@cindex @code{csrc_cl_N}
The @code{csrc} (an alias for @code{csrc_double}), @code{csrc_float},
@code{csrc_double} and @code{csrc_cl_N} manipulators set the output to a
format that can be directly used in a C or C++ program. The three possible
formats select the data types used for numbers (@code{csrc_cl_N} uses the
classes provided by the CLN library):
@example
// ...
cout << "f = " << csrc_float << e << ";\n";
cout << "d = " << csrc_double << e << ";\n";
cout << "n = " << csrc_cl_N << e << ";\n";
// ...
@end example
The above example will produce (note the @code{x^2} being converted to
@code{x*x}):
@example
f = (3.0/2.0)*(x*x)+std::complex<float>(0.0,4.5000000e+00);
d = (3.0/2.0)*(x*x)+std::complex<double>(0.0,4.5000000000000000e+00);
n = cln::cl_RA("3/2")*(x*x)+cln::complex(cln::cl_I("0"),cln::cl_F("4.5_17"));
@end example
@cindex @code{tree}
The @code{tree} manipulator allows dumping the internal structure of an
expression for debugging purposes:
@example
// ...
cout << tree << e;
@}
@end example
produces
@example
add, hash=0x0, flags=0x3, nops=2
power, hash=0x0, flags=0x3, nops=2
x (symbol), serial=0, hash=0xc8d5bcdd, flags=0xf
2 (numeric), hash=0x6526b0fa, flags=0xf
3/2 (numeric), hash=0xf9828fbd, flags=0xf
-----
overall_coeff
4.5L0i (numeric), hash=0xa40a97e0, flags=0xf
=====
@end example
@cindex @code{latex}
The @code{latex} output format is for LaTeX parsing in mathematical mode.
It is rather similar to the default format but provides some braces needed
by LaTeX for delimiting boxes and also converts some common objects to
conventional LaTeX names. It is possible to give symbols a special name for
LaTeX output by supplying it as a second argument to the @code{symbol}
constructor.
For example, the code snippet
@example
@{
symbol x("x", "\\circ");
ex e = lgamma(x).series(x==0,3);
cout << latex << e << endl;
@}
@end example
will print
@example
@{(-\ln(\circ))@}+@{(-\gamma_E)@} \circ+@{(\frac@{1@}@{12@} \pi^@{2@})@} \circ^@{2@}
+\mathcal@{O@}(\circ^@{3@})
@end example
@cindex @code{index_dimensions}
@cindex @code{no_index_dimensions}
Index dimensions are normally hidden in the output. To make them visible, use
the @code{index_dimensions} manipulator. The dimensions will be written in
square brackets behind each index value in the default and LaTeX output
formats:
@example
@{
symbol x("x"), y("y");
varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4);
ex e = indexed(x, mu) * indexed(y, nu);
cout << e << endl;
// prints 'x~mu*y~nu'
cout << index_dimensions << e << endl;
// prints 'x~mu[4]*y~nu[4]'
cout << no_index_dimensions << e << endl;
// prints 'x~mu*y~nu'
@}
@end example
@cindex Tree traversal
If you need any fancy special output format, e.g. for interfacing GiNaC
with other algebra systems or for producing code for different
programming languages, you can always traverse the expression tree yourself:
@example
static void my_print(const ex & e)
@{
if (is_a<function>(e))
cout << ex_to<function>(e).get_name();
else
cout << ex_to<basic>(e).class_name();
cout << "(";
size_t n = e.nops();
if (n)
for (size_t i=0; i<n; i++) @{
my_print(e.op(i));
if (i != n-1)
cout << ",";
@}
else
cout << e;
cout << ")";
@}
int main()
@{
my_print(pow(3, x) - 2 * sin(y / Pi)); cout << endl;
return 0;
@}
@end example
This will produce
@example
add(power(numeric(3),symbol(x)),mul(sin(mul(power(constant(Pi),numeric(-1)),
symbol(y))),numeric(-2)))
@end example
If you need an output format that makes it possible to accurately
reconstruct an expression by feeding the output to a suitable parser or
object factory, you should consider storing the expression in an
@code{archive} object and reading the object properties from there.
See the section on archiving for more information.
@subsection Expression input
@cindex input of expressions
GiNaC provides no way to directly read an expression from a stream because
you will usually want the user to be able to enter something like @samp{2*x+sin(y)}
and have the @samp{x} and @samp{y} correspond to the symbols @code{x} and
@code{y} you defined in your program and there is no way to specify the
desired symbols to the @code{>>} stream input operator.
Instead, GiNaC lets you read an expression from a stream or a string,
specifying the mapping between the input strings and symbols to be used:
@example
@{
symbol x, y;
symtab table;
table["x"] = x;
table["y"] = y;
parser reader(table);
ex e = reader("2*x+sin(y)");
@}
@end example
The input syntax is the same as that used by @command{ginsh} and the stream
output operator @code{<<}. Matching between the input strings and expressions
is given by @samp{table}. The @samp{table} in this example instructs GiNaC
to substitute any input substring ``x'' with symbol @code{x}. Likewise,
the substring ``y'' will be replaced with symbol @code{y}. It's also possible
to map input (sub)strings to arbitrary expressions:
@example
@{
symbol x, y;
symtab table;
table["x"] = x+log(y)+1;
parser reader(table);
ex e = reader("5*x^3 - x^2");
// e = 5*(x+log(y)+1)^3 + (x+log(y)+1)^2
@}
@end example
If no mapping is specified for a particular string GiNaC will create a symbol
with corresponding name. Later on you can obtain all parser generated symbols
with @code{get_syms()} method:
@example
@{
parser reader;
ex e = reader("2*x+sin(y)");
symtab table = reader.get_syms();
symbol x = reader["x"];
symbol y = reader["y"];
@}
@end example
Sometimes you might want to prevent GiNaC from inserting these extra symbols
(for example, you want treat an unexpected string in the input as an error).
@example
@{
symtab table;
table["x"] = symbol();
parser reader(table);
parser.strict = true;
ex e;
try @{
e = reader("2*x+sin(y)");
@} catch (parse_error& err) @{
cerr << err.what() << endl;
// prints "unknown symbol "y" in the input"
@}
@}
@end example
With this parser, it's also easy to implement interactive GiNaC programs:
@example
#include <iostream>
#include <string>
#include <stdexcept>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
int main()
@{
cout << "Enter an expression containing 'x': " << flush;
parser reader;
try @{
ex e = reader(cin);
symtab table = reader.get_syms();
symbol x = table.find("x") != table.end() ?
ex_to<symbol>(table["x"]) : symbol("x");
cout << "The derivative of " << e << " with respect to x is ";
cout << e.diff(x) << "." << endl;
@} catch (exception &p) @{
cerr << p.what() << endl;
@}
@}
@end example
@subsection Compiling expressions to C function pointers
@cindex compiling expressions
Numerical evaluation of algebraic expressions is seamlessly integrated into
GiNaC by help of the CLN library. While CLN allows for very fast arbitrary
precision numerics, which is more than sufficient for most users, sometimes only
the speed of built-in floating point numbers is fast enough, e.g. for Monte
Carlo integration. The only viable option then is the following: print the
expression in C syntax format, manually add necessary C code, compile that
program and run is as a separate application. This is not only cumbersome and
involves a lot of manual intervention, but it also separates the algebraic and
the numerical evaluation into different execution stages.
GiNaC offers a couple of functions that help to avoid these inconveniences and
problems. The functions automatically perform the printing of a GiNaC expression
and the subsequent compiling of its associated C code. The created object code
is then dynamically linked to the currently running program. A function pointer
to the C function that performs the numerical evaluation is returned and can be
used instantly. This all happens automatically, no user intervention is needed.
The following example demonstrates the use of @code{compile_ex}:
@example
// ...
symbol x("x");
ex myexpr = sin(x) / x;
FUNCP_1P fp;
compile_ex(myexpr, x, fp);
cout << fp(3.2) << endl;
// ...
@end example
The function @code{compile_ex} is called with the expression to be compiled and
its only free variable @code{x}. Upon successful completion the third parameter
contains a valid function pointer to the corresponding C code module. If called
like in the last line only built-in double precision numerics is involved.
@cindex FUNCP_1P
@cindex FUNCP_2P
@cindex FUNCP_CUBA
The function pointer has to be defined in advance. GiNaC offers three function
pointer types at the moment:
@example
typedef double (*FUNCP_1P) (double);
typedef double (*FUNCP_2P) (double, double);
typedef void (*FUNCP_CUBA) (const int*, const double[], const int*, double[]);
@end example
@cindex CUBA library
@cindex Monte Carlo integration
@code{FUNCP_2P} allows for two variables in the expression. @code{FUNCP_CUBA} is
the correct type to be used with the CUBA library
(@uref{http://www.feynarts.de/cuba}) for numerical integrations. The details for the
parameters of @code{FUNCP_CUBA} are explained in the CUBA manual.
@cindex compile_ex
For every function pointer type there is a matching @code{compile_ex} available:
@example
void compile_ex(const ex& expr, const symbol& sym, FUNCP_1P& fp,
const std::string filename = "");
void compile_ex(const ex& expr, const symbol& sym1, const symbol& sym2,
FUNCP_2P& fp, const std::string filename = "");
void compile_ex(const lst& exprs, const lst& syms, FUNCP_CUBA& fp,
const std::string filename = "");
@end example
When the last parameter @code{filename} is not supplied, @code{compile_ex} will
choose a unique random name for the intermediate source and object files it
produces. On program termination these files will be deleted. If one wishes to
keep the C code and the object files, one can supply the @code{filename}
parameter. The intermediate files will use that filename and will not be
deleted.
@cindex link_ex
@code{link_ex} is a function that allows to dynamically link an existing object
file and to make it available via a function pointer. This is useful if you
have already used @code{compile_ex} on an expression and want to avoid the
compilation step to be performed over and over again when you restart your
program. The precondition for this is of course, that you have chosen a
filename when you did call @code{compile_ex}. For every above mentioned
function pointer type there exists a corresponding @code{link_ex} function:
@example
void link_ex(const std::string filename, FUNCP_1P& fp);
void link_ex(const std::string filename, FUNCP_2P& fp);
void link_ex(const std::string filename, FUNCP_CUBA& fp);
@end example
The complete filename (including the suffix @code{.so}) of the object file has
to be supplied.
The function
@cindex unlink_ex
@example
void unlink_ex(const std::string filename);
@end example
is supplied for the rare cases when one wishes to close the dynamically linked
object files directly and have the intermediate files (only if filename has not
been given) deleted. Normally one doesn't need this function, because all the
clean-up will be done automatically upon (regular) program termination.
All the described functions will throw an exception in case they cannot perform
correctly, like for example when writing the file or starting the compiler
fails. Since internally the same printing methods as described in section
@ref{csrc printing} are used, only functions and objects that are available in
standard C will compile successfully (that excludes polylogarithms for example
at the moment). Another precondition for success is, of course, that it must be
possible to evaluate the expression numerically. No free variables despite the
ones supplied to @code{compile_ex} should appear in the expression.
@cindex ginac-excompiler
@code{compile_ex} uses the shell script @code{ginac-excompiler} to start the C
compiler and produce the object files. This shell script comes with GiNaC and
will be installed together with GiNaC in the configured @code{$PREFIX/bin}
directory.
@subsection Archiving
@cindex @code{archive} (class)
@cindex archiving
GiNaC allows creating @dfn{archives} of expressions which can be stored
to or retrieved from files. To create an archive, you declare an object
of class @code{archive} and archive expressions in it, giving each
expression a unique name:
@example
#include <fstream>
using namespace std;
#include <ginac/ginac.h>
using namespace GiNaC;
int main()
@{
symbol x("x"), y("y"), z("z");
ex foo = sin(x + 2*y) + 3*z + 41;
ex bar = foo + 1;
archive a;
a.archive_ex(foo, "foo");
a.archive_ex(bar, "the second one");
// ...
@end example
The archive can then be written to a file:
@example
// ...
ofstream out("foobar.gar");
out << a;
out.close();
// ...
@end example
The file @file{foobar.gar} contains all information that is needed to
reconstruct the expressions @code{foo} and @code{bar}.
@cindex @command{viewgar}
The tool @command{viewgar} that comes with GiNaC can be used to view
the contents of GiNaC archive files:
@example
$ viewgar foobar.gar
foo = 41+sin(x+2*y)+3*z
the second one = 42+sin(x+2*y)+3*z
@end example
The point of writing archive files is of course that they can later be
read in again:
@example
// ...
archive a2;
ifstream in("foobar.gar");
in >> a2;
// ...
@end example
And the stored expressions can be retrieved by their name:
@example
// ...
lst syms;
syms = x, y;
ex ex1 = a2.unarchive_ex(syms, "foo");
ex ex2 = a2.unarchive_ex(syms, "the second one");
cout << ex1 << endl; // prints "41+sin(x+2*y)+3*z"
cout << ex2 << endl; // prints "42+sin(x+2*y)+3*z"
cout << ex1.subs(x == 2) << endl; // prints "41+sin(2+2*y)+3*z"
@}
@end example
Note that you have to supply a list of the symbols which are to be inserted
in the expressions. Symbols in archives are stored by their name only and
if you don't specify which symbols you have, unarchiving the expression will
create new symbols with that name. E.g. if you hadn't included @code{x} in
the @code{syms} list above, the @code{ex1.subs(x == 2)} statement would
have had no effect because the @code{x} in @code{ex1} would have been a
different symbol than the @code{x} which was defined at the beginning of
the program, although both would appear as @samp{x} when printed.
You can also use the information stored in an @code{archive} object to
output expressions in a format suitable for exact reconstruction. The
@code{archive} and @code{archive_node} classes have a couple of member
functions that let you access the stored properties:
@example
static void my_print2(const archive_node & n)
@{
string class_name;
n.find_string("class", class_name);
cout << class_name << "(";
archive_node::propinfovector p;
n.get_properties(p);
size_t num = p.size();
for (size_t i=0; i<num; i++) @{
const string &name = p[i].name;
if (name == "class")
continue;
cout << name << "=";
unsigned count = p[i].count;
if (count > 1)
cout << "@{";
for (unsigned j=0; j<count; j++) @{
switch (p[i].type) @{
case archive_node::PTYPE_BOOL: @{
bool x;
n.find_bool(name, x, j);
cout << (x ? "true" : "false");
break;
@}
case archive_node::PTYPE_UNSIGNED: @{
unsigned x;
n.find_unsigned(name, x, j);
cout << x;
break;
@}
case archive_node::PTYPE_STRING: @{
string x;
n.find_string(name, x, j);
cout << '\"' << x << '\"';
break;
@}
case archive_node::PTYPE_NODE: @{
const archive_node &x = n.find_ex_node(name, j);
my_print2(x);
break;
@}
@}
if (j != count-1)
cout << ",";
@}
if (count > 1)
cout << "@}";
if (i != num-1)
cout << ",";
@}
cout << ")";
@}
int main()
@{
ex e = pow(2, x) - y;
archive ar(e, "e");
my_print2(ar.get_top_node(0)); cout << endl;
return 0;
@}
@end example
This will produce:
@example
add(rest=@{power(basis=numeric(number="2"),exponent=symbol(name="x")),
symbol(name="y")@},coeff=@{numeric(number="1"),numeric(number="-1")@},
overall_coeff=numeric(number="0"))
@end example
Be warned, however, that the set of properties and their meaning for each
class may change between GiNaC versions.
@node Extending GiNaC, What does not belong into GiNaC, Input/output, Top
@c node-name, next, previous, up
@chapter Extending GiNaC
By reading so far you should have gotten a fairly good understanding of
GiNaC's design patterns. From here on you should start reading the
sources. All we can do now is issue some recommendations how to tackle
GiNaC's many loose ends in order to fulfill everybody's dreams. If you
develop some useful extension please don't hesitate to contact the GiNaC
authors---they will happily incorporate them into future versions.
@menu
* What does not belong into GiNaC:: What to avoid.
* Symbolic functions:: Implementing symbolic functions.
* Printing:: Adding new output formats.
* Structures:: Defining new algebraic classes (the easy way).
* Adding classes:: Defining new algebraic classes (the hard way).
@end menu
@node What does not belong into GiNaC, Symbolic functions, Extending GiNaC, Extending GiNaC
@c node-name, next, previous, up
@section What doesn't belong into GiNaC
@cindex @command{ginsh}
First of all, GiNaC's name must be read literally. It is designed to be
a library for use within C++. The tiny @command{ginsh} accompanying
GiNaC makes this even more clear: it doesn't even attempt to provide a
language. There are no loops or conditional expressions in
@command{ginsh}, it is merely a window into the library for the
programmer to test stuff (or to show off). Still, the design of a
complete CAS with a language of its own, graphical capabilities and all
this on top of GiNaC is possible and is without doubt a nice project for
the future.
There are many built-in functions in GiNaC that do not know how to
evaluate themselves numerically to a precision declared at runtime
(using @code{Digits}). Some may be evaluated at certain points, but not
generally. This ought to be fixed. However, doing numerical
computations with GiNaC's quite abstract classes is doomed to be
inefficient. For this purpose, the underlying foundation classes
provided by CLN are much better suited.
@node Symbolic functions, Printing, What does not belong into GiNaC, Extending GiNaC
@c node-name, next, previous, up
@section Symbolic functions
The easiest and most instructive way to start extending GiNaC is probably to
create your own symbolic functions. These are implemented with the help of
two preprocessor macros:
@cindex @code{DECLARE_FUNCTION}
@cindex @code{REGISTER_FUNCTION}
@example
DECLARE_FUNCTION_<n>P(<name>)
REGISTER_FUNCTION(<name>, <options>)
@end example
The @code{DECLARE_FUNCTION} macro will usually appear in a header file. It
declares a C++ function with the given @samp{name} that takes exactly @samp{n}
parameters of type @code{ex} and returns a newly constructed GiNaC
@code{function} object that represents your function.
The @code{REGISTER_FUNCTION} macro implements the function. It must be passed
the same @samp{name} as the respective @code{DECLARE_FUNCTION} macro, and a
set of options that associate the symbolic function with C++ functions you
provide to implement the various methods such as evaluation, derivative,
series expansion etc. They also describe additional attributes the function
might have, such as symmetry and commutation properties, and a name for
LaTeX output. Multiple options are separated by the member access operator
@samp{.} and can be given in an arbitrary order.
(By the way: in case you are worrying about all the macros above we can
assure you that functions are GiNaC's most macro-intense classes. We have
done our best to avoid macros where we can.)
@subsection A minimal example
Here is an example for the implementation of a function with two arguments
that is not further evaluated:
@example
DECLARE_FUNCTION_2P(myfcn)
REGISTER_FUNCTION(myfcn, dummy())
@end example
Any code that has seen the @code{DECLARE_FUNCTION} line can use @code{myfcn()}
in algebraic expressions:
@example
@{
...
symbol x("x");
ex e = 2*myfcn(42, 1+3*x) - x;
cout << e << endl;
// prints '2*myfcn(42,1+3*x)-x'
...
@}
@end example
The @code{dummy()} option in the @code{REGISTER_FUNCTION} line signifies
"no options". A function with no options specified merely acts as a kind of
container for its arguments. It is a pure "dummy" function with no associated
logic (which is, however, sometimes perfectly sufficient).
Let's now have a look at the implementation of GiNaC's cosine function for an
example of how to make an "intelligent" function.
@subsection The cosine function
The GiNaC header file @file{inifcns.h} contains the line
@example
DECLARE_FUNCTION_1P(cos)
@end example
which declares to all programs using GiNaC that there is a function @samp{cos}
that takes one @code{ex} as an argument. This is all they need to know to use
this function in expressions.
The implementation of the cosine function is in @file{inifcns_trans.cpp}. Here
is its @code{REGISTER_FUNCTION} line:
@example
REGISTER_FUNCTION(cos, eval_func(cos_eval).
evalf_func(cos_evalf).
derivative_func(cos_deriv).
latex_name("\\cos"));
@end example
There are four options defined for the cosine function. One of them
(@code{latex_name}) gives the function a proper name for LaTeX output; the
other three indicate the C++ functions in which the "brains" of the cosine
function are defined.
@cindex @code{hold()}
@cindex evaluation
The @code{eval_func()} option specifies the C++ function that implements
the @code{eval()} method, GiNaC's anonymous evaluator. This function takes
the same number of arguments as the associated symbolic function (one in this
case) and returns the (possibly transformed or in some way simplified)
symbolically evaluated function (@xref{Automatic evaluation}, for a description
of the automatic evaluation process). If no (further) evaluation is to take
place, the @code{eval_func()} function must return the original function
with @code{.hold()}, to avoid a potential infinite recursion. If your
symbolic functions produce a segmentation fault or stack overflow when
using them in expressions, you are probably missing a @code{.hold()}
somewhere.
The @code{eval_func()} function for the cosine looks something like this
(actually, it doesn't look like this at all, but it should give you an idea
what is going on):
@example
static ex cos_eval(const ex & x)
@{
if ("x is a multiple of 2*Pi")
return 1;
else if ("x is a multiple of Pi")
return -1;
else if ("x is a multiple of Pi/2")
return 0;
// more rules...
else if ("x has the form 'acos(y)'")
return y;
else if ("x has the form 'asin(y)'")
return sqrt(1-y^2);
// more rules...
else
return cos(x).hold();
@}
@end example
This function is called every time the cosine is used in a symbolic expression:
@example
@{
...
e = cos(Pi);
// this calls cos_eval(Pi), and inserts its return value into
// the actual expression
cout << e << endl;
// prints '-1'
...
@}
@end example
In this way, @code{cos(4*Pi)} automatically becomes @math{1},
@code{cos(asin(a+b))} becomes @code{sqrt(1-(a+b)^2)}, etc. If no reasonable
symbolic transformation can be done, the unmodified function is returned
with @code{.hold()}.
GiNaC doesn't automatically transform @code{cos(2)} to @samp{-0.416146...}.
The user has to call @code{evalf()} for that. This is implemented in a
different function:
@example
static ex cos_evalf(const ex & x)
@{
if (is_a<numeric>(x))
return cos(ex_to<numeric>(x));
else
return cos(x).hold();
@}
@end example
Since we are lazy we defer the problem of numeric evaluation to somebody else,
in this case the @code{cos()} function for @code{numeric} objects, which in
turn hands it over to the @code{cos()} function in CLN. The @code{.hold()}
isn't really needed here, but reminds us that the corresponding @code{eval()}
function would require it in this place.
Differentiation will surely turn up and so we need to tell @code{cos}
what its first derivative is (higher derivatives, @code{.diff(x,3)} for
instance, are then handled automatically by @code{basic::diff} and
@code{ex::diff}):
@example
static ex cos_deriv(const ex & x, unsigned diff_param)
@{
return -sin(x);
@}
@end example
@cindex product rule
The second parameter is obligatory but uninteresting at this point. It
specifies which parameter to differentiate in a partial derivative in
case the function has more than one parameter, and its main application
is for correct handling of the chain rule.
An implementation of the series expansion is not needed for @code{cos()} as
it doesn't have any poles and GiNaC can do Taylor expansion by itself (as
long as it knows what the derivative of @code{cos()} is). @code{tan()}, on
the other hand, does have poles and may need to do Laurent expansion:
@example
static ex tan_series(const ex & x, const relational & rel,
int order, unsigned options)
@{
// Find the actual expansion point
const ex x_pt = x.subs(rel);
if ("x_pt is not an odd multiple of Pi/2")
throw do_taylor(); // tell function::series() to do Taylor expansion
// On a pole, expand sin()/cos()
return (sin(x)/cos(x)).series(rel, order+2, options);
@}
@end example
The @code{series()} implementation of a function @emph{must} return a
@code{pseries} object, otherwise your code will crash.
@subsection Function options
GiNaC functions understand several more options which are always
specified as @code{.option(params)}. None of them are required, but you
need to specify at least one option to @code{REGISTER_FUNCTION()}. There
is a do-nothing option called @code{dummy()} which you can use to define
functions without any special options.
@example
eval_func(<C++ function>)
evalf_func(<C++ function>)
derivative_func(<C++ function>)
series_func(<C++ function>)
conjugate_func(<C++ function>)
@end example
These specify the C++ functions that implement symbolic evaluation,
numeric evaluation, partial derivatives, and series expansion, respectively.
They correspond to the GiNaC methods @code{eval()}, @code{evalf()},
@code{diff()} and @code{series()}.
The @code{eval_func()} function needs to use @code{.hold()} if no further
automatic evaluation is desired or possible.
If no @code{series_func()} is given, GiNaC defaults to simple Taylor
expansion, which is correct if there are no poles involved. If the function
has poles in the complex plane, the @code{series_func()} needs to check
whether the expansion point is on a pole and fall back to Taylor expansion
if it isn't. Otherwise, the pole usually needs to be regularized by some
suitable transformation.
@example
latex_name(const string & n)
@end example
specifies the LaTeX code that represents the name of the function in LaTeX
output. The default is to put the function name in an @code{\mbox@{@}}.
@example
do_not_evalf_params()
@end example
This tells @code{evalf()} to not recursively evaluate the parameters of the
function before calling the @code{evalf_func()}.
@example
set_return_type(unsigned return_type, const return_type_t * return_type_tinfo)
@end example
This allows you to explicitly specify the commutation properties of the
function (@xref{Non-commutative objects}, for an explanation of
(non)commutativity in GiNaC). For example, with an object of type
@code{return_type_t} created like
@example
return_type_t my_type = make_return_type_t<matrix>();
@end example
you can use @code{set_return_type(return_types::noncommutative, &my_type)} to
make GiNaC treat your function like a matrix. By default, functions inherit the
commutation properties of their first argument. The utilized template function
@code{make_return_type_t<>()}
@example
template<typename T> inline return_type_t make_return_type_t(const unsigned rl = 0)
@end example
can also be called with an argument specifying the representation label of the
non-commutative function (see section on dirac gamma matrices for more
details).
@example
set_symmetry(const symmetry & s)
@end example
specifies the symmetry properties of the function with respect to its
arguments. @xref{Indexed objects}, for an explanation of symmetry
specifications. GiNaC will automatically rearrange the arguments of
symmetric functions into a canonical order.
Sometimes you may want to have finer control over how functions are
displayed in the output. For example, the @code{abs()} function prints
itself as @samp{abs(x)} in the default output format, but as @samp{|x|}
in LaTeX mode, and @code{fabs(x)} in C source output. This is achieved
with the
@example
print_func<C>(<C++ function>)
@end example
option which is explained in the next section.
@subsection Functions with a variable number of arguments
The @code{DECLARE_FUNCTION} and @code{REGISTER_FUNCTION} macros define
functions with a fixed number of arguments. Sometimes, though, you may need
to have a function that accepts a variable number of expressions. One way to
accomplish this is to pass variable-length lists as arguments. The
@code{Li()} function uses this method for multiple polylogarithms.
It is also possible to define functions that accept a different number of
parameters under the same function name, such as the @code{psi()} function
which can be called either as @code{psi(z)} (the digamma function) or as
@code{psi(n, z)} (polygamma functions). These are actually two different
functions in GiNaC that, however, have the same name. Defining such
functions is not possible with the macros but requires manually fiddling
with GiNaC internals. If you are interested, please consult the GiNaC source
code for the @code{psi()} function (@file{inifcns.h} and
@file{inifcns_gamma.cpp}).
@node Printing, Structures, Symbolic functions, Extending GiNaC
@c node-name, next, previous, up
@section GiNaC's expression output system
GiNaC allows the output of expressions in a variety of different formats
(@pxref{Input/output}). This section will explain how expression output
is implemented internally, and how to define your own output formats or
change the output format of built-in algebraic objects. You will also want
to read this section if you plan to write your own algebraic classes or
functions.
@cindex @code{print_context} (class)
@cindex @code{print_dflt} (class)
@cindex @code{print_latex} (class)
@cindex @code{print_tree} (class)
@cindex @code{print_csrc} (class)
All the different output formats are represented by a hierarchy of classes
rooted in the @code{print_context} class, defined in the @file{print.h}
header file:
@table @code
@item print_dflt
the default output format
@item print_latex
output in LaTeX mathematical mode
@item print_tree
a dump of the internal expression structure (for debugging)
@item print_csrc
the base class for C source output
@item print_csrc_float
C source output using the @code{float} type
@item print_csrc_double
C source output using the @code{double} type
@item print_csrc_cl_N
C source output using CLN types
@end table
The @code{print_context} base class provides two public data members:
@example
class print_context
@{
...
public:
std::ostream & s;
unsigned options;
@};
@end example
@code{s} is a reference to the stream to output to, while @code{options}
holds flags and modifiers. Currently, there is only one flag defined:
@code{print_options::print_index_dimensions} instructs the @code{idx} class
to print the index dimension which is normally hidden.
When you write something like @code{std::cout << e}, where @code{e} is
an object of class @code{ex}, GiNaC will construct an appropriate
@code{print_context} object (of a class depending on the selected output
format), fill in the @code{s} and @code{options} members, and call
@cindex @code{print()}
@example
void ex::print(const print_context & c, unsigned level = 0) const;
@end example
which in turn forwards the call to the @code{print()} method of the
top-level algebraic object contained in the expression.
Unlike other methods, GiNaC classes don't usually override their
@code{print()} method to implement expression output. Instead, the default
implementation @code{basic::print(c, level)} performs a run-time double
dispatch to a function selected by the dynamic type of the object and the
passed @code{print_context}. To this end, GiNaC maintains a separate method
table for each class, similar to the virtual function table used for ordinary
(single) virtual function dispatch.
The method table contains one slot for each possible @code{print_context}
type, indexed by the (internally assigned) serial number of the type. Slots
may be empty, in which case GiNaC will retry the method lookup with the
@code{print_context} object's parent class, possibly repeating the process
until it reaches the @code{print_context} base class. If there's still no
method defined, the method table of the algebraic object's parent class
is consulted, and so on, until a matching method is found (eventually it
will reach the combination @code{basic/print_context}, which prints the
object's class name enclosed in square brackets).
You can think of the print methods of all the different classes and output
formats as being arranged in a two-dimensional matrix with one axis listing
the algebraic classes and the other axis listing the @code{print_context}
classes.
Subclasses of @code{basic} can, of course, also overload @code{basic::print()}
to implement printing, but then they won't get any of the benefits of the
double dispatch mechanism (such as the ability for derived classes to
inherit only certain print methods from its parent, or the replacement of
methods at run-time).
@subsection Print methods for classes
The method table for a class is set up either in the definition of the class,
by passing the appropriate @code{print_func<C>()} option to
@code{GINAC_IMPLEMENT_REGISTERED_CLASS_OPT()} (@xref{Adding classes}, for
an example), or at run-time using @code{set_print_func<T, C>()}. The latter
can also be used to override existing methods dynamically.
The argument to @code{print_func<C>()} and @code{set_print_func<T, C>()} can
be a member function of the class (or one of its parent classes), a static
member function, or an ordinary (global) C++ function. The @code{C} template
parameter specifies the appropriate @code{print_context} type for which the
method should be invoked, while, in the case of @code{set_print_func<>()}, the
@code{T} parameter specifies the algebraic class (for @code{print_func<>()},
the class is the one being implemented by
@code{GINAC_IMPLEMENT_REGISTERED_CLASS_OPT}).
For print methods that are member functions, their first argument must be of
a type convertible to a @code{const C &}, and the second argument must be an
@code{unsigned}.
For static members and global functions, the first argument must be of a type
convertible to a @code{const T &}, the second argument must be of a type
convertible to a @code{const C &}, and the third argument must be an
@code{unsigned}. A global function will, of course, not have access to
private and protected members of @code{T}.
The @code{unsigned} argument of the print methods (and of @code{ex::print()}
and @code{basic::print()}) is used for proper parenthesizing of the output
(and by @code{print_tree} for proper indentation). It can be used for similar
purposes if you write your own output formats.
The explanations given above may seem complicated, but in practice it's
really simple, as shown in the following example. Suppose that we want to
display exponents in LaTeX output not as superscripts but with little
upwards-pointing arrows. This can be achieved in the following way:
@example
void my_print_power_as_latex(const power & p,
const print_latex & c,
unsigned level)
@{
// get the precedence of the 'power' class
unsigned power_prec = p.precedence();
// if the parent operator has the same or a higher precedence
// we need parentheses around the power
if (level >= power_prec)
c.s << '(';
// print the basis and exponent, each enclosed in braces, and
// separated by an uparrow
c.s << '@{';
p.op(0).print(c, power_prec);
c.s << "@}\\uparrow@{";
p.op(1).print(c, power_prec);
c.s << '@}';
// don't forget the closing parenthesis
if (level >= power_prec)
c.s << ')';
@}
int main()
@{
// a sample expression
symbol x("x"), y("y");
ex e = -3*pow(x, 3)*pow(y, -2) + pow(x+y, 2) - 1;
// switch to LaTeX mode
cout << latex;
// this prints "-1+@{(y+x)@}^@{2@}-3 \frac@{x^@{3@}@}@{y^@{2@}@}"
cout << e << endl;
// now we replace the method for the LaTeX output of powers with
// our own one
set_print_func<power, print_latex>(my_print_power_as_latex);
// this prints "-1+@{@{(y+x)@}@}\uparrow@{2@}-3 \frac@{@{x@}\uparrow@{3@}@}@{@{y@}
// \uparrow@{2@}@}"
cout << e << endl;
@}
@end example
Some notes:
@itemize
@item
The first argument of @code{my_print_power_as_latex} could also have been
a @code{const basic &}, the second one a @code{const print_context &}.
@item
The above code depends on @code{mul} objects converting their operands to
@code{power} objects for the purpose of printing.
@item
The output of products including negative powers as fractions is also
controlled by the @code{mul} class.
@item
The @code{power/print_latex} method provided by GiNaC prints square roots
using @code{\sqrt}, but the above code doesn't.
@end itemize
It's not possible to restore a method table entry to its previous or default
value. Once you have called @code{set_print_func()}, you can only override
it with another call to @code{set_print_func()}, but you can't easily go back
to the default behavior again (you can, of course, dig around in the GiNaC
sources, find the method that is installed at startup
(@code{power::do_print_latex} in this case), and @code{set_print_func} that
one; that is, after you circumvent the C++ member access control@dots{}).
@subsection Print methods for functions
Symbolic functions employ a print method dispatch mechanism similar to the
one used for classes. The methods are specified with @code{print_func<C>()}
function options. If you don't specify any special print methods, the function
will be printed with its name (or LaTeX name, if supplied), followed by a
comma-separated list of arguments enclosed in parentheses.
For example, this is what GiNaC's @samp{abs()} function is defined like:
@example
static ex abs_eval(const ex & arg) @{ ... @}
static ex abs_evalf(const ex & arg) @{ ... @}
static void abs_print_latex(const ex & arg, const print_context & c)
@{
c.s << "@{|"; arg.print(c); c.s << "|@}";
@}
static void abs_print_csrc_float(const ex & arg, const print_context & c)
@{
c.s << "fabs("; arg.print(c); c.s << ")";
@}
REGISTER_FUNCTION(abs, eval_func(abs_eval).
evalf_func(abs_evalf).
print_func<print_latex>(abs_print_latex).
print_func<print_csrc_float>(abs_print_csrc_float).
print_func<print_csrc_double>(abs_print_csrc_float));
@end example
This will display @samp{abs(x)} as @samp{|x|} in LaTeX mode and @code{fabs(x)}
in non-CLN C source output, but as @code{abs(x)} in all other formats.
There is currently no equivalent of @code{set_print_func()} for functions.
@subsection Adding new output formats
Creating a new output format involves subclassing @code{print_context},
which is somewhat similar to adding a new algebraic class
(@pxref{Adding classes}). There is a macro @code{GINAC_DECLARE_PRINT_CONTEXT}
that needs to go into the class definition, and a corresponding macro
@code{GINAC_IMPLEMENT_PRINT_CONTEXT} that has to appear at global scope.
Every @code{print_context} class needs to provide a default constructor
and a constructor from an @code{std::ostream} and an @code{unsigned}
options value.
Here is an example for a user-defined @code{print_context} class:
@example
class print_myformat : public print_dflt
@{
GINAC_DECLARE_PRINT_CONTEXT(print_myformat, print_dflt)
public:
print_myformat(std::ostream & os, unsigned opt = 0)
: print_dflt(os, opt) @{@}
@};
print_myformat::print_myformat() : print_dflt(std::cout) @{@}
GINAC_IMPLEMENT_PRINT_CONTEXT(print_myformat, print_dflt)
@end example
That's all there is to it. None of the actual expression output logic is
implemented in this class. It merely serves as a selector for choosing
a particular format. The algorithms for printing expressions in the new
format are implemented as print methods, as described above.
@code{print_myformat} is a subclass of @code{print_dflt}, so it behaves
exactly like GiNaC's default output format:
@example
@{
symbol x("x");
ex e = pow(x, 2) + 1;
// this prints "1+x^2"
cout << e << endl;
// this also prints "1+x^2"
e.print(print_myformat()); cout << endl;
...
@}
@end example
To fill @code{print_myformat} with life, we need to supply appropriate
print methods with @code{set_print_func()}, like this:
@example
// This prints powers with '**' instead of '^'. See the LaTeX output
// example above for explanations.
void print_power_as_myformat(const power & p,
const print_myformat & c,
unsigned level)
@{
unsigned power_prec = p.precedence();
if (level >= power_prec)
c.s << '(';
p.op(0).print(c, power_prec);
c.s << "**";
p.op(1).print(c, power_prec);
if (level >= power_prec)
c.s << ')';
@}
@{
...
// install a new print method for power objects
set_print_func<power, print_myformat>(print_power_as_myformat);
// now this prints "1+x**2"
e.print(print_myformat()); cout << endl;
// but the default format is still "1+x^2"
cout << e << endl;
@}
@end example
@node Structures, Adding classes, Printing, Extending GiNaC
@c node-name, next, previous, up
@section Structures
If you are doing some very specialized things with GiNaC, or if you just
need some more organized way to store data in your expressions instead of
anonymous lists, you may want to implement your own algebraic classes.
('algebraic class' means any class directly or indirectly derived from
@code{basic} that can be used in GiNaC expressions).
GiNaC offers two ways of accomplishing this: either by using the
@code{structure<T>} template class, or by rolling your own class from
scratch. This section will discuss the @code{structure<T>} template which
is easier to use but more limited, while the implementation of custom
GiNaC classes is the topic of the next section. However, you may want to
read both sections because many common concepts and member functions are
shared by both concepts, and it will also allow you to decide which approach
is most suited to your needs.
The @code{structure<T>} template, defined in the GiNaC header file
@file{structure.h}, wraps a type that you supply (usually a C++ @code{struct}
or @code{class}) into a GiNaC object that can be used in expressions.
@subsection Example: scalar products
Let's suppose that we need a way to handle some kind of abstract scalar
product of the form @samp{<x|y>} in expressions. Objects of the scalar
product class have to store their left and right operands, which can in turn
be arbitrary expressions. Here is a possible way to represent such a
product in a C++ @code{struct}:
@example
#include <iostream>
using namespace std;
#include <ginac/ginac.h>
using namespace GiNaC;
struct sprod_s @{
ex left, right;
sprod_s() @{@}
sprod_s(ex l, ex r) : left(l), right(r) @{@}
@};
@end example
The default constructor is required. Now, to make a GiNaC class out of this
data structure, we need only one line:
@example
typedef structure<sprod_s> sprod;
@end example
That's it. This line constructs an algebraic class @code{sprod} which
contains objects of type @code{sprod_s}. We can now use @code{sprod} in
expressions like any other GiNaC class:
@example
...
symbol a("a"), b("b");
ex e = sprod(sprod_s(a, b));
...
@end example
Note the difference between @code{sprod} which is the algebraic class, and
@code{sprod_s} which is the unadorned C++ structure containing the @code{left}
and @code{right} data members. As shown above, an @code{sprod} can be
constructed from an @code{sprod_s} object.
If you find the nested @code{sprod(sprod_s())} constructor too unwieldy,
you could define a little wrapper function like this:
@example
inline ex make_sprod(ex left, ex right)
@{
return sprod(sprod_s(left, right));
@}
@end example
The @code{sprod_s} object contained in @code{sprod} can be accessed with
the GiNaC @code{ex_to<>()} function followed by the @code{->} operator or
@code{get_struct()}:
@example
...
cout << ex_to<sprod>(e)->left << endl;
// -> a
cout << ex_to<sprod>(e).get_struct().right << endl;
// -> b
...
@end example
You only have read access to the members of @code{sprod_s}.
The type definition of @code{sprod} is enough to write your own algorithms
that deal with scalar products, for example:
@example
ex swap_sprod(ex p)
@{
if (is_a<sprod>(p)) @{
const sprod_s & sp = ex_to<sprod>(p).get_struct();
return make_sprod(sp.right, sp.left);
@} else
return p;
@}
...
f = swap_sprod(e);
// f is now <b|a>
...
@end example
@subsection Structure output
While the @code{sprod} type is useable it still leaves something to be
desired, most notably proper output:
@example
...
cout << e << endl;
// -> [structure object]
...
@end example
By default, any structure types you define will be printed as
@samp{[structure object]}. To override this you can either specialize the
template's @code{print()} member function, or specify print methods with
@code{set_print_func<>()}, as described in @ref{Printing}. Unfortunately,
it's not possible to supply class options like @code{print_func<>()} to
structures, so for a self-contained structure type you need to resort to
overriding the @code{print()} function, which is also what we will do here.
The member functions of GiNaC classes are described in more detail in the
next section, but it shouldn't be hard to figure out what's going on here:
@example
void sprod::print(const print_context & c, unsigned level) const
@{
// tree debug output handled by superclass
if (is_a<print_tree>(c))
inherited::print(c, level);
// get the contained sprod_s object
const sprod_s & sp = get_struct();
// print_context::s is a reference to an ostream
c.s << "<" << sp.left << "|" << sp.right << ">";
@}
@end example
Now we can print expressions containing scalar products:
@example
...
cout << e << endl;
// -> <a|b>
cout << swap_sprod(e) << endl;
// -> <b|a>
...
@end example
@subsection Comparing structures
The @code{sprod} class defined so far still has one important drawback: all
scalar products are treated as being equal because GiNaC doesn't know how to
compare objects of type @code{sprod_s}. This can lead to some confusing
and undesired behavior:
@example
...
cout << make_sprod(a, b) - make_sprod(a*a, b*b) << endl;
// -> 0
cout << make_sprod(a, b) + make_sprod(a*a, b*b) << endl;
// -> 2*<a|b> or 2*<a^2|b^2> (which one is undefined)
...
@end example
To remedy this, we first need to define the operators @code{==} and @code{<}
for objects of type @code{sprod_s}:
@example
inline bool operator==(const sprod_s & lhs, const sprod_s & rhs)
@{
return lhs.left.is_equal(rhs.left) && lhs.right.is_equal(rhs.right);
@}
inline bool operator<(const sprod_s & lhs, const sprod_s & rhs)
@{
return lhs.left.compare(rhs.left) < 0
? true : lhs.right.compare(rhs.right) < 0;
@}
@end example
The ordering established by the @code{<} operator doesn't have to make any
algebraic sense, but it needs to be well defined. Note that we can't use
expressions like @code{lhs.left == rhs.left} or @code{lhs.left < rhs.left}
in the implementation of these operators because they would construct
GiNaC @code{relational} objects which in the case of @code{<} do not
establish a well defined ordering (for arbitrary expressions, GiNaC can't
decide which one is algebraically 'less').
Next, we need to change our definition of the @code{sprod} type to let
GiNaC know that an ordering relation exists for the embedded objects:
@example
typedef structure<sprod_s, compare_std_less> sprod;
@end example
@code{sprod} objects then behave as expected:
@example
...
cout << make_sprod(a, b) - make_sprod(a*a, b*b) << endl;
// -> <a|b>-<a^2|b^2>
cout << make_sprod(a, b) + make_sprod(a*a, b*b) << endl;
// -> <a|b>+<a^2|b^2>
cout << make_sprod(a, b) - make_sprod(a, b) << endl;
// -> 0
cout << make_sprod(a, b) + make_sprod(a, b) << endl;
// -> 2*<a|b>
...
@end example
The @code{compare_std_less} policy parameter tells GiNaC to use the
@code{std::less} and @code{std::equal_to} functors to compare objects of
type @code{sprod_s}. By default, these functors forward their work to the
standard @code{<} and @code{==} operators, which we have overloaded.
Alternatively, we could have specialized @code{std::less} and
@code{std::equal_to} for class @code{sprod_s}.
GiNaC provides two other comparison policies for @code{structure<T>}
objects: the default @code{compare_all_equal}, and @code{compare_bitwise}
which does a bit-wise comparison of the contained @code{T} objects.
This should be used with extreme care because it only works reliably with
built-in integral types, and it also compares any padding (filler bytes of
undefined value) that the @code{T} class might have.
@subsection Subexpressions
Our scalar product class has two subexpressions: the left and right
operands. It might be a good idea to make them accessible via the standard
@code{nops()} and @code{op()} methods:
@example
size_t sprod::nops() const
@{
return 2;
@}
ex sprod::op(size_t i) const
@{
switch (i) @{
case 0:
return get_struct().left;
case 1:
return get_struct().right;
default:
throw std::range_error("sprod::op(): no such operand");
@}
@}
@end example
Implementing @code{nops()} and @code{op()} for container types such as
@code{sprod} has two other nice side effects:
@itemize @bullet
@item
@code{has()} works as expected
@item
GiNaC generates better hash keys for the objects (the default implementation
of @code{calchash()} takes subexpressions into account)
@end itemize
@cindex @code{let_op()}
There is a non-const variant of @code{op()} called @code{let_op()} that
allows replacing subexpressions:
@example
ex & sprod::let_op(size_t i)
@{
// every non-const member function must call this
ensure_if_modifiable();
switch (i) @{
case 0:
return get_struct().left;
case 1:
return get_struct().right;
default:
throw std::range_error("sprod::let_op(): no such operand");
@}
@}
@end example
Once we have provided @code{let_op()} we also get @code{subs()} and
@code{map()} for free. In fact, every container class that returns a non-null
@code{nops()} value must either implement @code{let_op()} or provide custom
implementations of @code{subs()} and @code{map()}.
In turn, the availability of @code{map()} enables the recursive behavior of a
couple of other default method implementations, in particular @code{evalf()},
@code{evalm()}, @code{normal()}, @code{diff()} and @code{expand()}. Although
we probably want to provide our own version of @code{expand()} for scalar
products that turns expressions like @samp{<a+b|c>} into @samp{<a|c>+<b|c>}.
This is left as an exercise for the reader.
The @code{structure<T>} template defines many more member functions that
you can override by specialization to customize the behavior of your
structures. You are referred to the next section for a description of
some of these (especially @code{eval()}). There is, however, one topic
that shall be addressed here, as it demonstrates one peculiarity of the
@code{structure<T>} template: archiving.
@subsection Archiving structures
If you don't know how the archiving of GiNaC objects is implemented, you
should first read the next section and then come back here. You're back?
Good.
To implement archiving for structures it is not enough to provide
specializations for the @code{archive()} member function and the
unarchiving constructor (the @code{unarchive()} function has a default
implementation). You also need to provide a unique name (as a string literal)
for each structure type you define. This is because in GiNaC archives,
the class of an object is stored as a string, the class name.
By default, this class name (as returned by the @code{class_name()} member
function) is @samp{structure} for all structure classes. This works as long
as you have only defined one structure type, but if you use two or more you
need to provide a different name for each by specializing the
@code{get_class_name()} member function. Here is a sample implementation
for enabling archiving of the scalar product type defined above:
@example
const char *sprod::get_class_name() @{ return "sprod"; @}
void sprod::archive(archive_node & n) const
@{
inherited::archive(n);
n.add_ex("left", get_struct().left);
n.add_ex("right", get_struct().right);
@}
sprod::structure(const archive_node & n, lst & sym_lst) : inherited(n, sym_lst)
@{
n.find_ex("left", get_struct().left, sym_lst);
n.find_ex("right", get_struct().right, sym_lst);
@}
@end example
Note that the unarchiving constructor is @code{sprod::structure} and not
@code{sprod::sprod}, and that we don't need to supply an
@code{sprod::unarchive()} function.
@node Adding classes, A comparison with other CAS, Structures, Extending GiNaC
@c node-name, next, previous, up
@section Adding classes
The @code{structure<T>} template provides an way to extend GiNaC with custom
algebraic classes that is easy to use but has its limitations, the most
severe of which being that you can't add any new member functions to
structures. To be able to do this, you need to write a new class definition
from scratch.
This section will explain how to implement new algebraic classes in GiNaC by
giving the example of a simple 'string' class. After reading this section
you will know how to properly declare a GiNaC class and what the minimum
required member functions are that you have to implement. We only cover the
implementation of a 'leaf' class here (i.e. one that doesn't contain
subexpressions). Creating a container class like, for example, a class
representing tensor products is more involved but this section should give
you enough information so you can consult the source to GiNaC's predefined
classes if you want to implement something more complicated.
@subsection Hierarchy of algebraic classes.
@cindex hierarchy of classes
All algebraic classes (that is, all classes that can appear in expressions)
in GiNaC are direct or indirect subclasses of the class @code{basic}. So a
@code{basic *} represents a generic pointer to an algebraic class. Working
with such pointers directly is cumbersome (think of memory management), hence
GiNaC wraps them into @code{ex} (@pxref{Expressions are reference counted}).
To make such wrapping possible every algebraic class has to implement several
methods. Visitors (@pxref{Visitors and tree traversal}), printing, and
(un)archiving (@pxref{Input/output}) require helper methods too. But don't
worry, most of the work is simplified by the following macros (defined
in @file{registrar.h}):
@itemize @bullet
@item @code{GINAC_DECLARE_REGISTERED_CLASS}
@item @code{GINAC_IMPLEMENT_REGISTERED_CLASS}
@item @code{GINAC_IMPLEMENT_REGISTERED_CLASS_OPT}
@end itemize
The @code{GINAC_DECLARE_REGISTERED_CLASS} macro inserts declarations
required for memory management, visitors, printing, and (un)archiving.
It takes the name of the class and its direct superclass as arguments.
The @code{GINAC_DECLARE_REGISTERED_CLASS} should be the first line after
the opening brace of the class definition.
@code{GINAC_IMPLEMENT_REGISTERED_CLASS} takes the same arguments as
@code{GINAC_DECLARE_REGISTERED_CLASS}. It initializes certain static
members of a class so that printing and (un)archiving works. The
@code{GINAC_IMPLEMENT_REGISTERED_CLASS} may appear anywhere else in
the source (at global scope, of course, not inside a function).
@code{GINAC_IMPLEMENT_REGISTERED_CLASS_OPT} is a variant of
@code{GINAC_IMPLEMENT_REGISTERED_CLASS}. It allows specifying additional
options, such as custom printing functions.
@subsection A minimalistic example
Now we will start implementing a new class @code{mystring} that allows
placing character strings in algebraic expressions (this is not very useful,
but it's just an example). This class will be a direct subclass of
@code{basic}. You can use this sample implementation as a starting point
for your own classes @footnote{The self-contained source for this example is
included in GiNaC, see the @file{doc/examples/mystring.cpp} file.}.
The code snippets given here assume that you have included some header files
as follows:
@example
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
#include <ginac/ginac.h>
using namespace GiNaC;
@end example
Now we can write down the class declaration. The class stores a C++
@code{string} and the user shall be able to construct a @code{mystring}
object from a string:
@example
class mystring : public basic
@{
GINAC_DECLARE_REGISTERED_CLASS(mystring, basic)
public:
mystring(const string & s);
private:
string str;
@};
GINAC_IMPLEMENT_REGISTERED_CLASS(mystring, basic)
@end example
The @code{GINAC_DECLARE_REGISTERED_CLASS} macro insert declarations required
for memory management, visitors, printing, and (un)archiving.
@code{GINAC_IMPLEMENT_REGISTERED_CLASS} initializes certain static members
of a class so that printing and (un)archiving works.
Now there are three member functions we have to implement to get a working
class:
@itemize
@item
@code{mystring()}, the default constructor.
@item
@cindex @code{compare_same_type()}
@code{int compare_same_type(const basic & other)}, which is used internally
by GiNaC to establish a canonical sort order for terms. It returns 0, +1 or
-1, depending on the relative order of this object and the @code{other}
object. If it returns 0, the objects are considered equal.
@strong{Please notice:} This has nothing to do with the (numeric) ordering
relationship expressed by @code{<}, @code{>=} etc (which cannot be defined
for non-numeric classes). For example, @code{numeric(1).compare_same_type(numeric(2))}
may return +1 even though 1 is clearly smaller than 2. Every GiNaC class
must provide a @code{compare_same_type()} function, even those representing
objects for which no reasonable algebraic ordering relationship can be
defined.
@item
And, of course, @code{mystring(const string& s)} which is the constructor
we declared.
@end itemize
Let's proceed step-by-step. The default constructor looks like this:
@example
mystring::mystring() @{ @}
@end example
In the default constructor you should set all other member variables to
reasonable default values (we don't need that here since our @code{str}
member gets set to an empty string automatically).
Our @code{compare_same_type()} function uses a provided function to compare
the string members:
@example
int mystring::compare_same_type(const basic & other) const
@{
const mystring &o = static_cast<const mystring &>(other);
int cmpval = str.compare(o.str);
if (cmpval == 0)
return 0;
else if (cmpval < 0)
return -1;
else
return 1;
@}
@end example
Although this function takes a @code{basic &}, it will always be a reference
to an object of exactly the same class (objects of different classes are not
comparable), so the cast is safe. If this function returns 0, the two objects
are considered equal (in the sense that @math{A-B=0}), so you should compare
all relevant member variables.
Now the only thing missing is our constructor:
@example
mystring::mystring(const string& s) : str(s) @{ @}
@end example
No surprises here. We set the @code{str} member from the argument.
That's it! We now have a minimal working GiNaC class that can store
strings in algebraic expressions. Let's confirm that the RTTI works:
@example
ex e = mystring("Hello, world!");
cout << is_a<mystring>(e) << endl;
// -> 1 (true)
cout << ex_to<basic>(e).class_name() << endl;
// -> mystring
@end example
Obviously it does. Let's see what the expression @code{e} looks like:
@example
cout << e << endl;
// -> [mystring object]
@end example
Hm, not exactly what we expect, but of course the @code{mystring} class
doesn't yet know how to print itself. This can be done either by implementing
the @code{print()} member function, or, preferably, by specifying a
@code{print_func<>()} class option. Let's say that we want to print the string
surrounded by double quotes:
@example
class mystring : public basic
@{
...
protected:
void do_print(const print_context & c, unsigned level = 0) const;
...
@};
void mystring::do_print(const print_context & c, unsigned level) const
@{
// print_context::s is a reference to an ostream
c.s << '\"' << str << '\"';
@}
@end example
The @code{level} argument is only required for container classes to
correctly parenthesize the output.
Now we need to tell GiNaC that @code{mystring} objects should use the
@code{do_print()} member function for printing themselves. For this, we
replace the line
@example
GINAC_IMPLEMENT_REGISTERED_CLASS(mystring, basic)
@end example
with
@example
GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring, basic,
print_func<print_context>(&mystring::do_print))
@end example
Let's try again to print the expression:
@example
cout << e << endl;
// -> "Hello, world!"
@end example
Much better. If we wanted to have @code{mystring} objects displayed in a
different way depending on the output format (default, LaTeX, etc.), we
would have supplied multiple @code{print_func<>()} options with different
template parameters (@code{print_dflt}, @code{print_latex}, etc.),
separated by dots. This is similar to the way options are specified for
symbolic functions. @xref{Printing}, for a more in-depth description of the
way expression output is implemented in GiNaC.
The @code{mystring} class can be used in arbitrary expressions:
@example
e += mystring("GiNaC rulez");
cout << e << endl;
// -> "GiNaC rulez"+"Hello, world!"
@end example
(GiNaC's automatic term reordering is in effect here), or even
@example
e = pow(mystring("One string"), 2*sin(Pi-mystring("Another string")));
cout << e << endl;
// -> "One string"^(2*sin(-"Another string"+Pi))
@end example
Whether this makes sense is debatable but remember that this is only an
example. At least it allows you to implement your own symbolic algorithms
for your objects.
Note that GiNaC's algebraic rules remain unchanged:
@example
e = mystring("Wow") * mystring("Wow");
cout << e << endl;
// -> "Wow"^2
e = pow(mystring("First")-mystring("Second"), 2);
cout << e.expand() << endl;
// -> -2*"First"*"Second"+"First"^2+"Second"^2
@end example
There's no way to, for example, make GiNaC's @code{add} class perform string
concatenation. You would have to implement this yourself.
@subsection Automatic evaluation
@cindex evaluation
@cindex @code{eval()}
@cindex @code{hold()}
When dealing with objects that are just a little more complicated than the
simple string objects we have implemented, chances are that you will want to
have some automatic simplifications or canonicalizations performed on them.
This is done in the evaluation member function @code{eval()}. Let's say that
we wanted all strings automatically converted to lowercase with
non-alphabetic characters stripped, and empty strings removed:
@example
class mystring : public basic
@{
...
public:
ex eval(int level = 0) const;
...
@};
ex mystring::eval(int level) const
@{
string new_str;
for (size_t i=0; i<str.length(); i++) @{
char c = str[i];
if (c >= 'A' && c <= 'Z')
new_str += tolower(c);
else if (c >= 'a' && c <= 'z')
new_str += c;
@}
if (new_str.length() == 0)
return 0;
else
return mystring(new_str).hold();
@}
@end example
The @code{level} argument is used to limit the recursion depth of the
evaluation. We don't have any subexpressions in the @code{mystring}
class so we are not concerned with this. If we had, we would call the
@code{eval()} functions of the subexpressions with @code{level - 1} as
the argument if @code{level != 1}. The @code{hold()} member function
sets a flag in the object that prevents further evaluation. Otherwise
we might end up in an endless loop. When you want to return the object
unmodified, use @code{return this->hold();}.
Let's confirm that it works:
@example
ex e = mystring("Hello, world!") + mystring("!?#");
cout << e << endl;
// -> "helloworld"
e = mystring("Wow!") + mystring("WOW") + mystring(" W ** o ** W");
cout << e << endl;
// -> 3*"wow"
@end example
@subsection Optional member functions
We have implemented only a small set of member functions to make the class
work in the GiNaC framework. There are two functions that are not strictly
required but will make operations with objects of the class more efficient:
@cindex @code{calchash()}
@cindex @code{is_equal_same_type()}
@example
unsigned calchash() const;
bool is_equal_same_type(const basic & other) const;
@end example
The @code{calchash()} method returns an @code{unsigned} hash value for the
object which will allow GiNaC to compare and canonicalize expressions much
more efficiently. You should consult the implementation of some of the built-in
GiNaC classes for examples of hash functions. The default implementation of
@code{calchash()} calculates a hash value out of the @code{tinfo_key} of the
class and all subexpressions that are accessible via @code{op()}.
@code{is_equal_same_type()} works like @code{compare_same_type()} but only
tests for equality without establishing an ordering relation, which is often
faster. The default implementation of @code{is_equal_same_type()} just calls
@code{compare_same_type()} and tests its result for zero.
@subsection Other member functions
For a real algebraic class, there are probably some more functions that you
might want to provide:
@example
bool info(unsigned inf) const;
ex evalf(int level = 0) const;
ex series(const relational & r, int order, unsigned options = 0) const;
ex derivative(const symbol & s) const;
@end example
If your class stores sub-expressions (see the scalar product example in the
previous section) you will probably want to override
@cindex @code{let_op()}
@example
size_t nops() cont;
ex op(size_t i) const;
ex & let_op(size_t i);
ex subs(const lst & ls, const lst & lr, unsigned options = 0) const;
ex map(map_function & f) const;
@end example
@code{let_op()} is a variant of @code{op()} that allows write access. The
default implementations of @code{subs()} and @code{map()} use it, so you have
to implement either @code{let_op()}, or @code{subs()} and @code{map()}.
You can, of course, also add your own new member functions. Remember
that the RTTI may be used to get information about what kinds of objects
you are dealing with (the position in the class hierarchy) and that you
can always extract the bare object from an @code{ex} by stripping the
@code{ex} off using the @code{ex_to<mystring>(e)} function when that
should become a need.
That's it. May the source be with you!
@subsection Upgrading extension classes from older version of GiNaC
GiNaC used to use a custom run time type information system (RTTI). It was
removed from GiNaC. Thus, one needs to rewrite constructors which set
@code{tinfo_key} (which does not exist any more). For example,
@example
myclass::myclass() : inherited(&myclass::tinfo_static) @{@}
@end example
needs to be rewritten as
@example
myclass::myclass() @{@}
@end example
@node A comparison with other CAS, Advantages, Adding classes, Top
@c node-name, next, previous, up
@chapter A Comparison With Other CAS
@cindex advocacy
This chapter will give you some information on how GiNaC compares to
other, traditional Computer Algebra Systems, like @emph{Maple},
@emph{Mathematica} or @emph{Reduce}, where it has advantages and
disadvantages over these systems.
@menu
* Advantages:: Strengths of the GiNaC approach.
* Disadvantages:: Weaknesses of the GiNaC approach.
* Why C++?:: Attractiveness of C++.
@end menu
@node Advantages, Disadvantages, A comparison with other CAS, A comparison with other CAS
@c node-name, next, previous, up
@section Advantages
GiNaC has several advantages over traditional Computer
Algebra Systems, like
@itemize @bullet
@item
familiar language: all common CAS implement their own proprietary
grammar which you have to learn first (and maybe learn again when your
vendor decides to `enhance' it). With GiNaC you can write your program
in common C++, which is standardized.
@cindex STL
@item
structured data types: you can build up structured data types using
@code{struct}s or @code{class}es together with STL features instead of
using unnamed lists of lists of lists.
@item
strongly typed: in CAS, you usually have only one kind of variables
which can hold contents of an arbitrary type. This 4GL like feature is
nice for novice programmers, but dangerous.
@item
development tools: powerful development tools exist for C++, like fancy
editors (e.g. with automatic indentation and syntax highlighting),
debuggers, visualization tools, documentation generators@dots{}
@item
modularization: C++ programs can easily be split into modules by
separating interface and implementation.
@item
price: GiNaC is distributed under the GNU Public License which means
that it is free and available with source code. And there are excellent
C++-compilers for free, too.
@item
extendable: you can add your own classes to GiNaC, thus extending it on
a very low level. Compare this to a traditional CAS that you can
usually only extend on a high level by writing in the language defined
by the parser. In particular, it turns out to be almost impossible to
fix bugs in a traditional system.
@item
multiple interfaces: Though real GiNaC programs have to be written in
some editor, then be compiled, linked and executed, there are more ways
to work with the GiNaC engine. Many people want to play with
expressions interactively, as in traditional CASs. Currently, two such
windows into GiNaC have been implemented and many more are possible: the
tiny @command{ginsh} that is part of the distribution exposes GiNaC's
types to a command line and second, as a more consistent approach, an
interactive interface to the Cint C++ interpreter has been put together
(called GiNaC-cint) that allows an interactive scripting interface
consistent with the C++ language. It is available from the usual GiNaC
FTP-site.
@item
seamless integration: it is somewhere between difficult and impossible
to call CAS functions from within a program written in C++ or any other
programming language and vice versa. With GiNaC, your symbolic routines
are part of your program. You can easily call third party libraries,
e.g. for numerical evaluation or graphical interaction. All other
approaches are much more cumbersome: they range from simply ignoring the
problem (i.e. @emph{Maple}) to providing a method for `embedding' the
system (i.e. @emph{Yacas}).
@item
efficiency: often large parts of a program do not need symbolic
calculations at all. Why use large integers for loop variables or
arbitrary precision arithmetics where @code{int} and @code{double} are
sufficient? For pure symbolic applications, GiNaC is comparable in
speed with other CAS.
@end itemize
@node Disadvantages, Why C++?, Advantages, A comparison with other CAS
@c node-name, next, previous, up
@section Disadvantages
Of course it also has some disadvantages:
@itemize @bullet
@item
advanced features: GiNaC cannot compete with a program like
@emph{Reduce} which exists for more than 30 years now or @emph{Maple}
which grows since 1981 by the work of dozens of programmers, with
respect to mathematical features. Integration,
non-trivial simplifications, limits etc. are missing in GiNaC (and are
not planned for the near future).
@item
portability: While the GiNaC library itself is designed to avoid any
platform dependent features (it should compile on any ANSI compliant C++
compiler), the currently used version of the CLN library (fast large
integer and arbitrary precision arithmetics) can only by compiled
without hassle on systems with the C++ compiler from the GNU Compiler
Collection (GCC).@footnote{This is because CLN uses PROVIDE/REQUIRE like
macros to let the compiler gather all static initializations, which
works for GNU C++ only. Feel free to contact the authors in case you
really believe that you need to use a different compiler. We have
occasionally used other compilers and may be able to give you advice.}
GiNaC uses recent language features like explicit constructors, mutable
members, RTTI, @code{dynamic_cast}s and STL, so ANSI compliance is meant
literally. Recent GCC versions starting at 2.95.3, although itself not
yet ANSI compliant, support all needed features.
@end itemize
@node Why C++?, Internal structures, Disadvantages, A comparison with other CAS
@c node-name, next, previous, up
@section Why C++?
Why did we choose to implement GiNaC in C++ instead of Java or any other
language? C++ is not perfect: type checking is not strict (casting is
possible), separation between interface and implementation is not
complete, object oriented design is not enforced. The main reason is
the often scolded feature of operator overloading in C++. While it may
be true that operating on classes with a @code{+} operator is rarely
meaningful, it is perfectly suited for algebraic expressions. Writing
@math{3x+5y} as @code{3*x+5*y} instead of
@code{x.times(3).plus(y.times(5))} looks much more natural.
Furthermore, the main developers are more familiar with C++ than with
any other programming language.
@node Internal structures, Expressions are reference counted, Why C++? , Top
@c node-name, next, previous, up
@appendix Internal structures
@menu
* Expressions are reference counted::
* Internal representation of products and sums::
@end menu
@node Expressions are reference counted, Internal representation of products and sums, Internal structures, Internal structures
@c node-name, next, previous, up
@appendixsection Expressions are reference counted
@cindex reference counting
@cindex copy-on-write
@cindex garbage collection
In GiNaC, there is an @emph{intrusive reference-counting} mechanism at work
where the counter belongs to the algebraic objects derived from class
@code{basic} but is maintained by the smart pointer class @code{ptr}, of
which @code{ex} contains an instance. If you understood that, you can safely
skip the rest of this passage.
Expressions are extremely light-weight since internally they work like
handles to the actual representation. They really hold nothing more
than a pointer to some other object. What this means in practice is
that whenever you create two @code{ex} and set the second equal to the
first no copying process is involved. Instead, the copying takes place
as soon as you try to change the second. Consider the simple sequence
of code:
@example
#include <iostream>
#include <ginac/ginac.h>
using namespace std;
using namespace GiNaC;
int main()
@{
symbol x("x"), y("y"), z("z");
ex e1, e2;
e1 = sin(x + 2*y) + 3*z + 41;
e2 = e1; // e2 points to same object as e1
cout << e2 << endl; // prints sin(x+2*y)+3*z+41
e2 += 1; // e2 is copied into a new object
cout << e2 << endl; // prints sin(x+2*y)+3*z+42
@}
@end example
The line @code{e2 = e1;} creates a second expression pointing to the
object held already by @code{e1}. The time involved for this operation
is therefore constant, no matter how large @code{e1} was. Actual
copying, however, must take place in the line @code{e2 += 1;} because
@code{e1} and @code{e2} are not handles for the same object any more.
This concept is called @dfn{copy-on-write semantics}. It increases
performance considerably whenever one object occurs multiple times and
represents a simple garbage collection scheme because when an @code{ex}
runs out of scope its destructor checks whether other expressions handle
the object it points to too and deletes the object from memory if that
turns out not to be the case. A slightly less trivial example of
differentiation using the chain-rule should make clear how powerful this
can be:
@example
@{
symbol x("x"), y("y");
ex e1 = x + 3*y;
ex e2 = pow(e1, 3);
ex e3 = diff(sin(e2), x); // first derivative of sin(e2) by x
cout << e1 << endl // prints x+3*y
<< e2 << endl // prints (x+3*y)^3
<< e3 << endl; // prints 3*(x+3*y)^2*cos((x+3*y)^3)
@}
@end example
Here, @code{e1} will actually be referenced three times while @code{e2}
will be referenced two times. When the power of an expression is built,
that expression needs not be copied. Likewise, since the derivative of
a power of an expression can be easily expressed in terms of that
expression, no copying of @code{e1} is involved when @code{e3} is
constructed. So, when @code{e3} is constructed it will print as
@code{3*(x+3*y)^2*cos((x+3*y)^3)} but the argument of @code{cos()} only
holds a reference to @code{e2} and the factor in front is just
@code{3*e1^2}.
As a user of GiNaC, you cannot see this mechanism of copy-on-write
semantics. When you insert an expression into a second expression, the
result behaves exactly as if the contents of the first expression were
inserted. But it may be useful to remember that this is not what
happens. Knowing this will enable you to write much more efficient
code. If you still have an uncertain feeling with copy-on-write
semantics, we recommend you have a look at the
@uref{http://www.parashift.com/c++-faq-lite/, C++-FAQ lite} by
Marshall Cline. Chapter 16 covers this issue and presents an
implementation which is pretty close to the one in GiNaC.
@node Internal representation of products and sums, Package tools, Expressions are reference counted, Internal structures
@c node-name, next, previous, up
@appendixsection Internal representation of products and sums
@cindex representation
@cindex @code{add}
@cindex @code{mul}
@cindex @code{power}
Although it should be completely transparent for the user of
GiNaC a short discussion of this topic helps to understand the sources
and also explain performance to a large degree. Consider the
unexpanded symbolic expression
@tex
$2d^3 \left( 4a + 5b - 3 \right)$
@end tex
@ifnottex
@math{2*d^3*(4*a+5*b-3)}
@end ifnottex
which could naively be represented by a tree of linear containers for
addition and multiplication, one container for exponentiation with base
and exponent and some atomic leaves of symbols and numbers in this
fashion:
@ifnotinfo
@image{repnaive}
@end ifnotinfo
@ifinfo
<PICTURE MISSING>
@end ifinfo
@cindex pair-wise representation
However, doing so results in a rather deeply nested tree which will
quickly become inefficient to manipulate. We can improve on this by
representing the sum as a sequence of terms, each one being a pair of a
purely numeric multiplicative coefficient and its rest. In the same
spirit we can store the multiplication as a sequence of terms, each
having a numeric exponent and a possibly complicated base, the tree
becomes much more flat:
@ifnotinfo
@image{reppair}
@end ifnotinfo
@ifinfo
<PICTURE MISSING>
@end ifinfo
The number @code{3} above the symbol @code{d} shows that @code{mul}
objects are treated similarly where the coefficients are interpreted as
@emph{exponents} now. Addition of sums of terms or multiplication of
products with numerical exponents can be coded to be very efficient with
such a pair-wise representation. Internally, this handling is performed
by most CAS in this way. It typically speeds up manipulations by an
order of magnitude. The overall multiplicative factor @code{2} and the
additive term @code{-3} look somewhat out of place in this
representation, however, since they are still carrying a trivial
exponent and multiplicative factor @code{1} respectively. Within GiNaC,
this is avoided by adding a field that carries an overall numeric
coefficient. This results in the realistic picture of internal
representation for
@tex
$2d^3 \left( 4a + 5b - 3 \right)$:
@end tex
@ifnottex
@math{2*d^3*(4*a+5*b-3)}:
@end ifnottex
@ifnotinfo
@image{repreal}
@end ifnotinfo
@ifinfo
<PICTURE MISSING>
@end ifinfo
@cindex radical
This also allows for a better handling of numeric radicals, since
@code{sqrt(2)} can now be carried along calculations. Now it should be
clear, why both classes @code{add} and @code{mul} are derived from the
same abstract class: the data representation is the same, only the
semantics differs. In the class hierarchy, methods for polynomial
expansion and the like are reimplemented for @code{add} and @code{mul},
but the data structure is inherited from @code{expairseq}.
@node Package tools, Configure script options, Internal representation of products and sums, Top
@c node-name, next, previous, up
@appendix Package tools
If you are creating a software package that uses the GiNaC library,
setting the correct command line options for the compiler and linker can
be difficult. The @command{pkg-config} utility makes this process
easier. GiNaC supplies all necessary data in @file{ginac.pc} (installed
into @code{/usr/local/lib/pkgconfig} by default). To compile a simple
program use @footnote{If GiNaC is installed into some non-standard
directory @var{prefix} one should set the @var{PKG_CONFIG_PATH}
environment variable to @var{prefix}/lib/pkgconfig for this to work.}
@example
g++ -o simple `pkg-config --cflags --libs ginac` simple.cpp
@end example
This command line might expand to (for example):
@example
g++ -o simple -lginac -lcln simple.cpp
@end example
Not only is the form using @command{pkg-config} easier to type, it will
work on any system, no matter how GiNaC was configured.
For packages configured using GNU automake, @command{pkg-config} also
provides the @code{PKG_CHECK_MODULES} macro to automate the process of
checking for libraries
@example
PKG_CHECK_MODULES(MYAPP, ginac >= MINIMUM_VERSION,
[@var{ACTION-IF-FOUND}],
[@var{ACTION-IF-NOT-FOUND}])
@end example
This macro:
@itemize @bullet
@item
Determines the location of GiNaC using data from @file{ginac.pc}, which is
either found in the default @command{pkg-config} search path, or from
the environment variable @env{PKG_CONFIG_PATH}.
@item
Tests the installed libraries to make sure that their version
is later than @var{MINIMUM-VERSION}.
@item
If the required version was found, sets the @env{MYAPP_CFLAGS} variable
to the output of @command{pkg-config --cflags ginac} and the @env{MYAPP_LIBS}
variable to the output of @command{pkg-config --libs ginac}, and calls
@samp{AC_SUBST()} for these variables so they can be used in generated
makefiles, and then executes @var{ACTION-IF-FOUND}.
@item
If the required version was not found, executes @var{ACTION-IF-NOT-FOUND}.
@end itemize
@menu
* Configure script options:: Configuring a package that uses GiNaC
* Example package:: Example of a package using GiNaC
@end menu
@node Configure script options, Example package, Package tools, Package tools
@c node-name, next, previous, up
@subsection Configuring a package that uses GiNaC
The directory where the GiNaC libraries are installed needs
to be found by your system's dynamic linkers (both compile- and run-time
ones). See the documentation of your system linker for details. Also
make sure that @file{ginac.pc} is in @command{pkg-config}'s search path,
@xref{pkg-config, ,pkg-config, *manpages*}.
The short summary below describes how to do this on a GNU/Linux
system.
Suppose GiNaC is installed into the directory @samp{PREFIX}. To tell
the linkers where to find the library one should
@itemize @bullet
@item
edit @file{/etc/ld.so.conf} and run @command{ldconfig}. For example,
@example
# echo PREFIX/lib >> /etc/ld.so.conf
# ldconfig
@end example
@item
or set the environment variables @env{LD_LIBRARY_PATH} and @env{LD_RUN_PATH}
@example
$ export LD_LIBRARY_PATH=PREFIX/lib
$ export LD_RUN_PATH=PREFIX/lib
@end example
@item
or give a @samp{-L} and @samp{--rpath} flags when running configure,
for instance:
@example
$ LDFLAGS='-Wl,-LPREFIX/lib -Wl,--rpath=PREFIX/lib' ./configure
@end example
@end itemize
To tell @command{pkg-config} where the @file{ginac.pc} file is,
set the @env{PKG_CONFIG_PATH} environment variable:
@example
$ export PKG_CONFIG_PATH=PREFIX/lib/pkgconfig
@end example
Finally, run the @command{configure} script
@example
$ ./configure
@end example
@c There are many other ways to do the same, @xref{Options, ,Command Line Options, ld, GNU ld manual}.
@node Example package, Bibliography, Configure script options, Package tools
@c node-name, next, previous, up
@subsection Example of a package using GiNaC
The following shows how to build a simple package using automake
and the @samp{PKG_CHECK_MODULES} macro. The program used here is @file{simple.cpp}:
@example
#include <iostream>
#include <ginac/ginac.h>
int main()
@{
GiNaC::symbol x("x");
GiNaC::ex a = GiNaC::sin(x);
std::cout << "Derivative of " << a
<< " is " << a.diff(x) << std::endl;
return 0;
@}
@end example
You should first read the introductory portions of the automake
Manual, if you are not already familiar with it.
Two files are needed, @file{configure.ac}, which is used to build the
configure script:
@example
dnl Process this file with autoreconf to produce a configure script.
AC_INIT([simple], 1.0.0, bogus@@example.net)
AC_CONFIG_SRCDIR(simple.cpp)
AM_INIT_AUTOMAKE([foreign 1.8])
AC_PROG_CXX
AC_PROG_INSTALL
AC_LANG([C++])
PKG_CHECK_MODULES(SIMPLE, ginac >= 1.3.7)
AC_OUTPUT(Makefile)
@end example
The @samp{PKG_CHECK_MODULES} macro does the following: If a GiNaC version
greater or equal than 1.3.7 is found, then it defines @var{SIMPLE_CFLAGS}
and @var{SIMPLE_LIBS}. Otherwise, it dies with the error message like
@example
configure: error: Package requirements (ginac >= 1.3.7) were not met:
Requested 'ginac >= 1.3.7' but version of GiNaC is 1.3.5
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
Alternatively, you may set the environment variables SIMPLE_CFLAGS
and SIMPLE_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
@end example
And the @file{Makefile.am}, which will be used to build the Makefile.
@example
## Process this file with automake to produce Makefile.in
bin_PROGRAMS = simple
simple_SOURCES = simple.cpp
simple_CPPFLAGS = $(SIMPLE_CFLAGS)
simple_LDADD = $(SIMPLE_LIBS)
@end example
This @file{Makefile.am}, says that we are building a single executable,
from a single source file @file{simple.cpp}. Since every program
we are building uses GiNaC we could have simply added @var{SIMPLE_CFLAGS}
to @var{CPPFLAGS} and @var{SIMPLE_LIBS} to @var{LIBS}. However, it is
more flexible to specify libraries and complier options on a per-program
basis.
To try this example out, create a new directory and add the three
files above to it.
Now execute the following command:
@example
$ autoreconf -i
@end example
You now have a package that can be built in the normal fashion
@example
$ ./configure
$ make
$ make install
@end example
@node Bibliography, Concept index, Example package, Top
@c node-name, next, previous, up
@appendix Bibliography
@itemize @minus{}
@item
@cite{ISO/IEC 14882:1998: Programming Languages: C++}
@item
@cite{CLN: A Class Library for Numbers}, @email{haible@@ilog.fr, Bruno Haible}
@item
@cite{The C++ Programming Language}, Bjarne Stroustrup, 3rd Edition, ISBN 0-201-88954-4, Addison Wesley
@item
@cite{C++ FAQs}, Marshall Cline, ISBN 0-201-58958-3, 1995, Addison Wesley
@item
@cite{Algorithms for Computer Algebra}, Keith O. Geddes, Stephen R. Czapor,
and George Labahn, ISBN 0-7923-9259-0, 1992, Kluwer Academic Publishers, Norwell, Massachusetts
@item
@cite{Computer Algebra: Systems and Algorithms for Algebraic Computation},
James H. Davenport, Yvon Siret and Evelyne Tournier, ISBN 0-12-204230-1, 1988,
Academic Press, London
@item
@cite{Computer Algebra Systems - A Practical Guide},
Michael J. Wester (editor), ISBN 0-471-98353-5, 1999, Wiley, Chichester
@item
@cite{The Art of Computer Programming, Vol 2: Seminumerical Algorithms},
Donald E. Knuth, ISBN 0-201-89684-2, 1998, Addison Wesley
@item
@cite{Pi Unleashed}, J@"org Arndt and Christoph Haenel,
ISBN 3-540-66572-2, 2001, Springer, Heidelberg
@item
@cite{The Role of gamma5 in Dimensional Regularization}, Dirk Kreimer, hep-ph/9401354
@end itemize
@node Concept index, , Bibliography, Top
@c node-name, next, previous, up
@unnumbered Concept index
@printindex cp
@bye
|