/usr/include/trilinos/Tpetra_CrsMatrix_def.hpp is in libtrilinos-tpetra-dev 12.4.2-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | // @HEADER
// ***********************************************************************
//
// Tpetra: Templated Linear Algebra Services Package
// Copyright (2008) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
// @HEADER
#ifndef TPETRA_CRSMATRIX_DEF_HPP
#define TPETRA_CRSMATRIX_DEF_HPP
/// \file Tpetra_MultiVector_def.hpp
/// \brief Definition of the Tpetra::MultiVector class
///
/// If you want to use Tpetra::CrsMatrix, include
/// "Tpetra_CrsMatrix.hpp" (a file which CMake generates and installs
/// for you). If you only want the declaration of Tpetra::CrsMatrix,
/// include "Tpetra_CrsMatrix_decl.hpp".
#include "Tpetra_RowMatrix.hpp"
#include "Tpetra_Import_Util.hpp"
#include "Tpetra_Import_Util2.hpp"
#include "Tpetra_Util.hpp"
#include "Teuchos_SerialDenseMatrix.hpp"
#include "Teuchos_as.hpp"
#include "Teuchos_ArrayRCP.hpp"
#include <typeinfo>
// CrsMatrix relies on template methods implemented in Tpetra_CrsGraph_def.hpp
//
// FIXME (mfh 01 Oct 2015) If I comment this out, I get link errors
// for CrsGraph's templated methods, even though supposedly the ETI
// for CrsGraph instantiates them.
#include "Tpetra_CrsGraph_def.hpp"
namespace Tpetra {
//
// Users must never rely on anything in the Details namespace.
//
namespace Details {
/// \struct AbsMax
/// \brief Functor for the the ABSMAX CombineMode of Import and Export operations.
/// \tparam Scalar Same as the Scalar template parameter of CrsMatrix.
///
/// \warning This is an implementation detail of CrsMatrix. Users
/// must not rely on this class. It may disappear or its
/// interface may change at any time.
///
/// \tparam Scalar Same as the Scalar template parameter of CrsMatrix.
template<class Scalar>
struct AbsMax {
//! Return the maximum of the magnitudes (absolute values) of x and y.
Scalar operator() (const Scalar& x, const Scalar& y) {
typedef Teuchos::ScalarTraits<Scalar> STS;
return std::max (STS::magnitude (x), STS::magnitude (y));
}
};
/// \struct CrsIJV
/// \brief Struct representing a sparse matrix entry as an i,j,v triplet.
/// \tparam Ordinal Same as the GlobalOrdinal template parameter of CrsMatrix.
/// \tparam Scalar Same as the Scalar template parameter of CrsMatrix.
///
/// \warning This is an implementation detail of CrsMatrix. Users
/// must not rely on this class. It may disappear or its
/// interface may change at any time.
///
/// CrsMatrix uses this struct to communicate nonlocal sparse
/// matrix entries in its globalAssemble() method.
template <class Ordinal, class Scalar>
struct CrsIJV {
/// \brief Default constructor
///
/// This constructor sets the row and column indices to
/// <tt>Teuchos::OrdinalTraits<Ordinal>::invalid()</tt>, as a
/// clear sign that they were not initialized.
CrsIJV () :
i (Teuchos::OrdinalTraits<Ordinal>::invalid ()),
j (Teuchos::OrdinalTraits<Ordinal>::invalid ()),
v (Teuchos::ScalarTraits<Scalar>::zero ())
{}
/// \brief Standard constructor
///
/// \param row [in] (Global) row index
/// \param col [in] (Global) column index
/// \param val [in] Value of matrix entry
CrsIJV (Ordinal row, Ordinal col, const Scalar &val) :
i (row), j (col), v (val)
{}
/// \brief Comparison operator
///
/// Comparison operator for sparse matrix entries stored as
/// (i,j,v) triples. Defining this lets Tpetra::CrsMatrix use
/// std::sort to sort CrsIJV instances.
bool operator< (const CrsIJV<Ordinal, Scalar>& rhs) const {
// FIXME (mfh 10 May 2013): This is what I found when I moved
// this operator out of the std namespace to be an instance
// method of CrsIJV. It's a little odd to me that it doesn't
// include the column index in the sort order (for the usual
// lexicographic sort). It doesn't really matter because
// CrsMatrix will sort rows by column index anyway, but it's
// still odd.
return this->i < rhs.i;
}
Ordinal i; //!< (Global) row index
Ordinal j; //!< (Global) column index
Scalar v; //!< Value of matrix entry
};
} // namespace Details
} // namespace Tpetra
namespace Teuchos {
// SerializationTraits specialization for Tpetra::Details::CrsIJV.
//
// Tpetra::Details::CrsIJV can be serialized using
// DirectSerialization. This lets Comm send and receive instances
// of this class.
//
// NOTE (mfh 16 Dec 2012): This won't work if Scalar does not
// support direct serialization ("just taking the address"). The
// usual Scalar types (float, double, dd_real, qd_real, or
// std::complex<T> for any of these types) _do_ support direct
// serialization.
template <typename Ordinal, typename Scalar>
class SerializationTraits<int, Tpetra::Details::CrsIJV<Ordinal, Scalar> >
: public DirectSerializationTraits<int, Tpetra::Details::CrsIJV<Ordinal, Scalar> >
{};
} // namespace Teuchos
namespace Tpetra {
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
size_t maxNumEntriesPerRow,
ProfileType pftype,
const RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
storageStatus_ (pftype == StaticProfile ?
Details::STORAGE_1D_UNPACKED :
Details::STORAGE_2D),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::rcp;
try {
myGraph_ = rcp (new crs_graph_type (rowMap, maxNumEntriesPerRow,
pftype, params));
}
catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix constructor: Caught "
"exception while allocating CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
resumeFill (params);
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
const Teuchos::ArrayRCP<const size_t>& NumEntriesPerRowToAlloc,
ProfileType pftype,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
storageStatus_ (pftype == StaticProfile ?
Details::STORAGE_1D_UNPACKED :
Details::STORAGE_2D),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::rcp;
try {
myGraph_ = rcp (new Graph (rowMap, NumEntriesPerRowToAlloc, pftype, params));
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix constructor: Caught "
"exception while allocating CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
resumeFill (params);
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
const Teuchos::RCP<const map_type>& colMap,
size_t maxNumEntriesPerRow,
ProfileType pftype,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
storageStatus_ (pftype == StaticProfile ?
Details::STORAGE_1D_UNPACKED :
Details::STORAGE_2D),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::rcp;
TEUCHOS_TEST_FOR_EXCEPTION(! staticGraph_.is_null(), std::logic_error,
"Tpetra::CrsMatrix ctor (row Map, col Map, maxNumEntriesPerRow, ...): "
"staticGraph_ is not null at the beginning of the constructor. "
"Please report this bug to the Tpetra developers.");
TEUCHOS_TEST_FOR_EXCEPTION(! myGraph_.is_null(), std::logic_error,
"Tpetra::CrsMatrix ctor (row Map, col Map, maxNumEntriesPerRow, ...): "
"myGraph_ is not null at the beginning of the constructor. "
"Please report this bug to the Tpetra developers.");
try {
myGraph_ = rcp (new Graph (rowMap, colMap, maxNumEntriesPerRow,
pftype, params));
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix constructor: Caught "
"exception while allocating CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
resumeFill (params);
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
const Teuchos::RCP<const map_type>& colMap,
const Teuchos::ArrayRCP<const size_t>& numEntPerRow,
ProfileType pftype,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
storageStatus_ (pftype == StaticProfile ?
Details::STORAGE_1D_UNPACKED :
Details::STORAGE_2D),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::rcp;
try {
myGraph_ = rcp (new Graph (rowMap, colMap, numEntPerRow, pftype, params));
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix constructor: Caught "
"exception while allocating CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
resumeFill (params);
checkInternalState ();
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const crs_graph_type>& graph,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (graph->getRowMap ()),
staticGraph_ (graph),
storageStatus_ (Details::STORAGE_1D_PACKED),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
const char tfecfFuncName[] = "CrsMatrix(graph[,params])";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(staticGraph_.is_null (),
std::runtime_error, ": When calling the CrsMatrix constructor that "
"accepts a static graph, the pointer to the graph must not be null.");
// We prohibit the case where the graph is not yet filled.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( ! staticGraph_->isFillComplete (),
std::runtime_error, ": The specified graph is not fill-complete. You "
"must invoke fillComplete() on the graph before using it to construct a "
"CrsMatrix. Note that calling resumeFill() makes the graph not fill-"
"complete, even if you had previously called fillComplete(). In that "
"case, you must call fillComplete() on the graph again.");
// the graph has entries, and the matrix should have entries as well, set to zero. no need or point in lazy allocating in this case.
// first argument LocalIndices is ignored; the graph is already allocated (local or global, we don't care here)
allocateValues (LocalIndices, GraphAlreadyAllocated);
resumeFill (params);
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
const Teuchos::RCP<const map_type>& colMap,
const typename local_matrix_type::row_map_type& rowPointers,
const typename local_graph_type::entries_type::non_const_type& columnIndices,
const typename local_matrix_type::values_type& values,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
storageStatus_ (Details::STORAGE_1D_PACKED),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::rcp;
try {
myGraph_ = rcp (new Graph (rowMap, colMap, rowPointers,
columnIndices, params));
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix constructor: Caught "
"exception while allocating CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
k_values1D_ = values;
resumeFill (params);
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
const Teuchos::RCP<const map_type>& colMap,
const Teuchos::ArrayRCP<size_t> & rowPointers,
const Teuchos::ArrayRCP<LocalOrdinal> & columnIndices,
const Teuchos::ArrayRCP<Scalar> & values,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
storageStatus_ (Details::STORAGE_1D_PACKED),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::rcp;
try {
myGraph_ = rcp (new Graph (rowMap, colMap, rowPointers,
columnIndices, params));
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix constructor: Caught "
"exception while allocating CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
// FIXME (mfh 05 Aug 2014) It should be possible to convince the
// ArrayRCP to relinquish its allocation, but that might require
// passing the ArrayRCP in by nonconst reference.
Teuchos::ArrayRCP<impl_scalar_type> vals =
Teuchos::arcp_reinterpret_cast<impl_scalar_type> (values);
k_values1D_ = Kokkos::Compat::getKokkosViewDeepCopy<device_type> (vals ());
resumeFill (params);
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
CrsMatrix (const Teuchos::RCP<const map_type>& rowMap,
const Teuchos::RCP<const map_type>& colMap,
const local_matrix_type& lclMatrix,
const Teuchos::RCP<Teuchos::ParameterList>& params) :
dist_object_type (rowMap),
lclMatrix_ (lclMatrix),
storageStatus_ (Details::STORAGE_1D_PACKED),
fillComplete_ (false),
frobNorm_ (-STM::one ())
{
using Teuchos::ArrayRCP;
using Teuchos::arcp;
using Teuchos::rcp;
using Teuchos::RCP;
const char tfecfFuncName[] = "Tpetra::CrsMatrix(rowMap,colMap,lclMatrix,params): ";
try {
myGraph_ = rcp (new Graph (rowMap, colMap, lclMatrix.graph, params));
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::runtime_error, "Caught exception while allocating "
"CrsGraph: " << e.what ());
}
staticGraph_ = myGraph_;
computeGlobalConstants ();
k_values1D_ = lclMatrix_.values;
// FIXME (mfh 28 Aug 2014) "Preserve Local Graph" bool parameter no longer used.
// Now we're fill complete!
fillComplete_ = true;
// Sanity checks at the end.
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(isFillActive (), std::logic_error,
"We're at the end of fillComplete(), but isFillActive() is true. "
"Please report this bug to the Tpetra developers.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! isFillComplete (), std::logic_error,
"We're at the end of fillComplete(), but isFillComplete() is false. "
"Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
checkInternalState ();
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
~CrsMatrix ()
{}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const Teuchos::Comm<int> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getComm () const {
return getCrsGraph ()->getComm ();
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<Node>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNode () const {
return getCrsGraph ()->getNode ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
ProfileType
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getProfileType () const {
return getCrsGraph ()->getProfileType ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isFillComplete () const {
return fillComplete_;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isFillActive () const {
return ! fillComplete_;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isStorageOptimized () const {
return getCrsGraph()->isStorageOptimized();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isLocallyIndexed () const {
return getCrsGraph ()->isLocallyIndexed ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isGloballyIndexed () const {
return getCrsGraph ()->isGloballyIndexed ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
hasColMap () const {
return getCrsGraph ()->hasColMap ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
global_size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalNumEntries () const {
return getCrsGraph ()->getGlobalNumEntries ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNodeNumEntries () const {
return getCrsGraph ()->getNodeNumEntries ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
global_size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalNumRows () const {
return getCrsGraph ()->getGlobalNumRows ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
global_size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalNumCols () const {
return getCrsGraph ()->getGlobalNumCols ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNodeNumRows () const {
return getCrsGraph ()->getNodeNumRows ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNodeNumCols () const {
return getCrsGraph ()->getNodeNumCols ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
global_size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalNumDiags () const {
return getCrsGraph ()->getGlobalNumDiags ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNodeNumDiags () const {
return getCrsGraph ()->getNodeNumDiags ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNumEntriesInGlobalRow (GlobalOrdinal globalRow) const {
return getCrsGraph ()->getNumEntriesInGlobalRow (globalRow);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNumEntriesInLocalRow (LocalOrdinal localRow) const {
return getCrsGraph ()->getNumEntriesInLocalRow (localRow);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalMaxNumRowEntries () const {
return getCrsGraph ()->getGlobalMaxNumRowEntries ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
size_t
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getNodeMaxNumRowEntries () const {
return getCrsGraph ()->getNodeMaxNumRowEntries ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
GlobalOrdinal
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getIndexBase () const {
return getRowMap ()->getIndexBase ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getRowMap () const {
return getCrsGraph ()->getRowMap ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getColMap () const {
return getCrsGraph ()->getColMap ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getDomainMap () const {
return getCrsGraph ()->getDomainMap ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getRangeMap () const {
return getCrsGraph()->getRangeMap();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const RowGraph<LocalOrdinal, GlobalOrdinal, Node> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGraph () const {
if (staticGraph_ != Teuchos::null) {
return staticGraph_;
}
return myGraph_;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<const CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getCrsGraph () const {
if (staticGraph_ != Teuchos::null) {
return staticGraph_;
}
return myGraph_;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isLowerTriangular () const {
return getCrsGraph ()->isLowerTriangular ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isUpperTriangular () const {
return getCrsGraph ()->isUpperTriangular ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
isStaticGraph () const {
return myGraph_.is_null ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
hasTransposeApply () const {
return true;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
supportsRowViews () const {
return true;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
allocateValues (ELocalGlobal lg, GraphAllocationStatus gas)
{
#ifdef HAVE_TPETRA_DEBUG
// If the graph indices are already allocated, then gas should be
// GraphAlreadyAllocated. Otherwise, gas should be
// GraphNotYetAllocated.
if ((gas == GraphAlreadyAllocated) != staticGraph_->indicesAreAllocated()) {
const std::string err1 ("allocateValues: The caller has asserted that "
"the graph is ");
const std::string err2 ("already allocated, but the static graph says "
"that its indices are ");
const std::string err3 ("already allocated. Please report this bug to "
"the Tpetra developers.");
TEUCHOS_TEST_FOR_EXCEPTION(gas == GraphAlreadyAllocated && ! staticGraph_->indicesAreAllocated(),
std::logic_error, err1 << err2 << "not " << err3);
TEUCHOS_TEST_FOR_EXCEPTION(gas != GraphAlreadyAllocated && staticGraph_->indicesAreAllocated(),
std::logic_error, err1 << "not " << err2 << err3);
}
// If the graph is unallocated, then it had better be a
// matrix-owned graph. ("Matrix-owned graph" means that the
// matrix gets to define the graph structure. If the CrsMatrix
// constructor that takes an RCP<const CrsGraph> was used, then
// the matrix does _not_ own the graph.)
TEUCHOS_TEST_FOR_EXCEPTION(
! staticGraph_->indicesAreAllocated() && myGraph_.is_null(),
std::logic_error,
"allocateValues: The static graph says that its indices are not "
"allocated, but the graph is not owned by the matrix. Please report "
"this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
if (gas == GraphNotYetAllocated) {
myGraph_->allocateIndices (lg);
}
// Allocate matrix values.
if (getProfileType () == StaticProfile) {
// "Static profile" means that the number of matrix entries in
// each row was fixed at the time the CrsMatrix constructor was
// called. This lets us use 1-D storage for the matrix's
// values. ("1-D storage" means the same as that used by the
// three arrays in the classic compressed sparse row format.)
const size_t lclNumRows = staticGraph_->getNodeNumRows ();
typename Graph::local_graph_type::row_map_type k_ptrs =
staticGraph_->k_rowPtrs_;
TEUCHOS_TEST_FOR_EXCEPTION(
k_ptrs.dimension_0 () != lclNumRows+1, std::logic_error,
"Tpetra::CrsMatrix::allocateValues: With StaticProfile, row offsets "
"array has length " << k_ptrs.dimension_0 () << " != (lclNumRows+1) = "
<< (lclNumRows+1) << ".");
// FIXME (mfh 08 Aug 2014) This assumes UVM. We could fix this
// either by storing the row offsets in the graph as a DualView,
// or by making a device View of that entry, and copying it back
// to host.
const size_t lclTotalNumEntries = k_ptrs(lclNumRows);
// Allocate array of (packed???) matrix values.
typedef typename local_matrix_type::values_type values_type;
k_values1D_ = values_type ("Tpetra::CrsMatrix::val", lclTotalNumEntries);
}
else {
// "Dynamic profile" means the number of matrix entries in each
// row is not fixed and may expand. Thus, we store the matrix's
// values in "2-D storage," meaning an array of arrays. The
// outer array has as many inner arrays as there are rows in the
// matrix, and each inner array stores the values in that row.
values2D_ = staticGraph_->template allocateValues2D<impl_scalar_type> ();
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getAllValues (Teuchos::ArrayRCP<const size_t>& rowPointers,
Teuchos::ArrayRCP<const LocalOrdinal>& columnIndices,
Teuchos::ArrayRCP<const Scalar>& values) const
{
const char tfecfFuncName[] = "getAllValues: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
columnIndices.size () != values.size (), std::runtime_error,
"Requires that columnIndices and values are the same size.");
RCP<const crs_graph_type> relevantGraph = getCrsGraph ();
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
relevantGraph.is_null (), std::runtime_error,
"Requires that getCrsGraph() is not null.");
try {
rowPointers = relevantGraph->getNodeRowPtrs ();
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::runtime_error,
"Caught exception while calling graph->getNodeRowPtrs(): "
<< e.what ());
}
try {
columnIndices = relevantGraph->getNodePackedIndices ();
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::runtime_error,
"Caught exception while calling graph->getNodePackedIndices(): "
<< e.what ());
}
Teuchos::ArrayRCP<const impl_scalar_type> vals =
Kokkos::Compat::persistingView (k_values1D_);
values = Teuchos::arcp_reinterpret_cast<const Scalar> (vals);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
fillLocalGraphAndMatrix (const Teuchos::RCP<Teuchos::ParameterList>& params)
{
using Kokkos::create_mirror_view;
using Teuchos::arcp_const_cast;
using Teuchos::ArrayRCP;
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
typedef ArrayRCP<size_t>::size_type size_type;
typedef typename local_matrix_type::row_map_type row_map_type;
typedef typename Graph::t_numRowEntries_ row_entries_type;
typedef typename Graph::local_graph_type::entries_type::non_const_type lclinds_1d_type;
typedef typename local_matrix_type::values_type values_type;
// fillComplete() only calls fillLocalGraphAndMatrix() if the
// matrix owns the graph, which means myGraph_ is not null.
TEUCHOS_TEST_FOR_EXCEPTION(
myGraph_.is_null (), std::logic_error, "Tpetra::CrsMatrix::"
"fillLocalGraphAndMatrix (called from fillComplete or "
"expertStaticFillComplete): The nonconst graph (myGraph_) is null. This "
"means that the matrix has a const (a.k.a. \"static\") graph. This may "
"mean that fillComplete or expertStaticFillComplete has a bug, since it "
"should never call fillLocalGraphAndMatrix in that case. "
"Please report this bug to the Tpetra developers.");
const size_t lclNumRows = this->getNodeNumRows ();
// This method's goal is to fill in the three arrays (compressed
// sparse row format) that define the sparse graph's and matrix's
// structure, and the sparse matrix's values.
//
// Use the nonconst version of row_map_type for k_ptrs,
// because row_map_type is const and we need to modify k_ptrs here.
typename row_map_type::non_const_type k_ptrs;
row_map_type k_ptrs_const;
lclinds_1d_type k_inds;
values_type k_vals;
// Get references to the data in myGraph_, so we can modify them
// as well. Note that we only call fillLocalGraphAndMatrix() if
// the matrix owns the graph, which means myGraph_ is not null.
lclinds_1d_type k_lclInds1D_ = myGraph_->k_lclInds1D_;
// The number of entries in each locally owned row. This is a
// DualView. 2-D storage lives on host and is currently not
// thread-safe for parallel kernels even on host, so we have to
// work sequentially with host storage in that case.
row_entries_type k_numRowEnt = myGraph_->k_numRowEntries_;
typename row_entries_type::t_host h_numRowEnt = k_numRowEnt.h_view;
if (getProfileType () == DynamicProfile) {
// Pack 2-D storage (DynamicProfile) into 1-D packed storage.
//
// DynamicProfile means that the matrix's column indices and
// values are currently stored in a 2-D "unpacked" format, in
// the arrays-of-arrays myGraph_->lclInds2D_ (for column
// indices) and values2D_ (for values). We allocate 1-D storage
// (k_inds resp. k_vals), and then copy from 2-D storage
// (lclInds2D_ resp. values2D_) into 1-D storage (k_inds
// resp. k_vals).
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_numRowEnt.dimension_0 ()) != lclNumRows,
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix (called "
"from fillComplete or expertStaticFillComplete): For the "
"DynamicProfile branch, k_numRowEnt has the wrong length. "
"k_numRowEnt.dimension_0() = " << k_numRowEnt.dimension_0 ()
<< " != getNodeNumRows() = " << lclNumRows << "");
// Pack the row offsets into k_ptrs, by doing a sum-scan of
// the array of valid entry counts per row (h_numRowEnt).
//
// Total number of entries in the matrix on the calling
// process. We will compute this in the loop below. It's
// cheap to compute and useful as a sanity check.
size_t lclTotalNumEntries = 0;
// This will be a host view of packed row offsets.
typename row_map_type::non_const_type::HostMirror h_ptrs;
{
// Allocate the packed row offsets array. We use a nonconst
// temporary (packedRowOffsets) here, because k_ptrs is const.
// We will assign packedRowOffsets to k_ptrs below.
typename row_map_type::non_const_type packedRowOffsets ("Tpetra::CrsGraph::ptr",
lclNumRows+1);
//
// FIXME hack until we get parallel_scan in kokkos
//
h_ptrs = create_mirror_view (packedRowOffsets);
h_ptrs(0) = 0;
for (size_type i = 0; i < static_cast<size_type> (lclNumRows); ++i) {
const size_t numEnt = h_numRowEnt(i);
lclTotalNumEntries += numEnt;
h_ptrs(i+1) = h_ptrs(i) + numEnt;
}
Kokkos::deep_copy (packedRowOffsets, h_ptrs);
// packedRowOffsets is modifiable; k_ptrs isn't, so we have to
// use packedRowOffsets in the loop above and assign here.
k_ptrs = packedRowOffsets;
k_ptrs_const = k_ptrs;
}
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs.dimension_0 ()) != lclNumRows + 1,
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: In "
"DynamicProfile branch, after packing k_ptrs, k_ptrs.dimension_0()"
" = " << k_ptrs.dimension_0 () << " != (lclNumRows+1) = "
<< (lclNumRows+1) << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (h_ptrs.dimension_0 ()) != lclNumRows + 1,
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: In "
"DynamicProfile branch, after packing h_ptrs, h_ptrs.dimension_0()"
" = " << h_ptrs.dimension_0 () << " != (lclNumRows+1) = "
<< (lclNumRows+1) << ".");
// FIXME (mfh 08 Aug 2014) This assumes UVM.
TEUCHOS_TEST_FOR_EXCEPTION(
k_ptrs(lclNumRows) != lclTotalNumEntries, std::logic_error,
"Tpetra::CrsMatrix::fillLocalGraphAndMatrix: In DynamicProfile branch, "
"after packing k_ptrs, k_ptrs(lclNumRows = " << lclNumRows << ") = " <<
k_ptrs(lclNumRows) << " != total number of entries on the calling "
"process = " << lclTotalNumEntries << ".");
// Allocate the arrays of packed column indices and values.
k_inds = lclinds_1d_type ("Tpetra::CrsGraph::ind", lclTotalNumEntries);
k_vals = values_type ("Tpetra::CrsMatrix::val", lclTotalNumEntries);
// We need host views of the above, since 2-D storage lives on host.
typename lclinds_1d_type::HostMirror h_inds = create_mirror_view (k_inds);
typename values_type::HostMirror h_vals = create_mirror_view (k_vals);
// Pack the column indices and values on the host.
ArrayRCP<Array<LocalOrdinal> > lclInds2D = myGraph_->lclInds2D_;
for (size_t row = 0; row < lclNumRows; ++row) {
const size_t numEnt = h_numRowEnt(row);
std::copy (lclInds2D[row].begin(),
lclInds2D[row].begin() + numEnt,
h_inds.ptr_on_device() + h_ptrs(row));
std::copy (values2D_[row].begin(),
values2D_[row].begin() + numEnt,
h_vals.ptr_on_device() + h_ptrs(row));
}
// Copy the packed column indices and values to the device.
Kokkos::deep_copy (k_inds, h_inds);
Kokkos::deep_copy (k_vals, h_vals);
// Sanity check of packed row offsets.
if (k_ptrs.dimension_0 () != 0) {
const size_t numOffsets = static_cast<size_t> (k_ptrs.dimension_0 ());
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs(numOffsets-1)) != k_vals.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In DynamicProfile branch, after packing, k_ptrs(" << (numOffsets-1)
<< ") = " << k_ptrs(numOffsets-1) << " != k_vals.dimension_0() = "
<< k_vals.dimension_0 () << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs(numOffsets-1)) != k_inds.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In DynamicProfile branch, after packing, k_ptrs(" << (numOffsets-1)
<< ") = " << k_ptrs(numOffsets-1) << " != k_inds.dimension_0() = "
<< k_inds.dimension_0 () << ".");
}
}
else if (getProfileType () == StaticProfile) {
// StaticProfile means that the matrix's column indices and
// values are currently stored in a 1-D format, with row offsets
// in k_rowPtrs_ and local column indices in k_lclInds1D_.
// StaticProfile also means that the graph's array of row
// offsets must already be allocated.
typename Graph::local_graph_type::row_map_type curRowOffsets =
myGraph_->k_rowPtrs_;
TEUCHOS_TEST_FOR_EXCEPTION(
curRowOffsets.dimension_0 () == 0, std::logic_error,
"curRowOffsets has size zero, but shouldn't");
TEUCHOS_TEST_FOR_EXCEPTION(
curRowOffsets.dimension_0 () != lclNumRows + 1, std::logic_error,
"Tpetra::CrsMatrix::fillLocalGraphAndMatrix: curRowOffsets has size "
<< curRowOffsets.dimension_0 () << " != lclNumRows + 1 = "
<< (lclNumRows + 1) << ".")
{
const size_t numOffsets = curRowOffsets.dimension_0 ();
// FIXME (mfh 06 Aug 2014) This relies on UVM.
TEUCHOS_TEST_FOR_EXCEPTION(
numOffsets != 0 &&
myGraph_->k_lclInds1D_.dimension_0 () != curRowOffsets(numOffsets - 1),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"numOffsets = " << numOffsets << " != 0 and "
"myGraph_->k_lclInds1D_.dimension_0() = "
<< myGraph_->k_lclInds1D_.dimension_0 ()
<< " != curRowOffsets(" << numOffsets << ") = "
<< curRowOffsets(numOffsets - 1) << ".");
}
if (myGraph_->nodeNumEntries_ != myGraph_->nodeNumAllocated_) {
// The matrix's current 1-D storage is "unpacked." This means
// the row offsets may differ from what the final row offsets
// should be. This could happen, for example, if the user
// specified StaticProfile in the constructor and set an upper
// bound on the number of entries per row, but didn't fill all
// those entries.
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_numRowEnt.dimension_0 ()) != lclNumRows,
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix (called"
" from fillComplete or expertStaticFillComplete): In StaticProfile "
"unpacked branch, k_numRowEnt has the wrong length. "
"k_numRowEnt.dimension_0() = " << k_numRowEnt.dimension_0 ()
<< " != getNodeNumRows() = " << lclNumRows << ".");
if (curRowOffsets.dimension_0 () != 0) {
const size_t numOffsets =
static_cast<size_t> (curRowOffsets.dimension_0 ());
TEUCHOS_TEST_FOR_EXCEPTION(
curRowOffsets(numOffsets-1) != static_cast<size_t> (k_values1D_.dimension_0 ()),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In StaticProfile branch, before allocating or packing, "
"curRowOffsets(" << (numOffsets-1) << ") = "
<< curRowOffsets(numOffsets - 1)
<< " != k_values1D_.dimension_0() = "
<< k_values1D_.dimension_0 () << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (curRowOffsets(numOffsets - 1)) !=
myGraph_->k_lclInds1D_.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In StaticProfile branch, before allocating or packing, "
"curRowOffsets(" << (numOffsets-1) << ") = "
<< curRowOffsets(numOffsets - 1)
<< " != myGraph_->k_lclInds1D_.dimension_0() = "
<< myGraph_->k_lclInds1D_.dimension_0 () << ".");
}
// Pack the row offsets into k_ptrs, by doing a sum-scan of
// the array of valid entry counts per row (h_numRowEnt).
// Total number of entries in the matrix on the calling
// process. We will compute this in the loop below. It's
// cheap to compute and useful as a sanity check.
size_t lclTotalNumEntries = 0;
// This will be a host view of packed row offsets.
typename row_map_type::non_const_type::HostMirror h_ptrs;
{
// Allocate the packed row offsets array. We use a nonconst
// temporary (packedRowOffsets) here, because k_ptrs is
// const. We will assign packedRowOffsets to k_ptrs below.
typename row_map_type::non_const_type packedRowOffsets ("Tpetra::CrsGraph::ptr",
lclNumRows+1);
//
// FIXME hack until we get parallel_scan in Kokkos
//
// Unlike in the 2-D storage case above, we don't need the
// host view of the packed row offsets array after packing
// the row offsets.
h_ptrs = create_mirror_view (packedRowOffsets);
h_ptrs(0) = 0;
for (size_type i = 0; i < static_cast<size_type> (lclNumRows); ++i) {
const size_t numEnt = h_numRowEnt(i);
lclTotalNumEntries += numEnt;
h_ptrs(i+1) = h_ptrs(i) + numEnt;
}
Kokkos::deep_copy (packedRowOffsets, h_ptrs);
// packedRowOffsets is modifiable; k_ptrs isn't, so we have
// to use packedRowOffsets in the loop above and assign here.
k_ptrs = packedRowOffsets;
k_ptrs_const = k_ptrs;
}
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs.dimension_0 ()) != lclNumRows + 1,
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: For "
"the StaticProfile unpacked-but-pack branch, after packing k_ptrs, "
"k_ptrs.dimension_0() = " << k_ptrs.dimension_0 () << " != "
"lclNumRows+1 = " << (lclNumRows+1) << ".");
// FIXME (mfh 06 Aug 2014) This assumes UVM.
TEUCHOS_TEST_FOR_EXCEPTION(
k_ptrs(lclNumRows) != lclTotalNumEntries, std::logic_error,
"Tpetra::CrsMatrix::fillLocalGraphAndMatrix: In StaticProfile "
"unpacked-but-pack branch, after filling k_ptrs, k_ptrs(lclNumRows="
<< lclNumRows << ") = " << k_ptrs(lclNumRows) << " != total number "
"of entries on the calling process = " << lclTotalNumEntries << ".");
// Allocate the arrays of packed column indices and values.
k_inds = lclinds_1d_type ("Tpetra::CrsGraph::ind", lclTotalNumEntries);
k_vals = values_type ("Tpetra::CrsMatrix::val", lclTotalNumEntries);
// curRowOffsets (myGraph_->k_rowPtrs_) (???), k_lclInds1D_,
// and k_values1D_ are currently unpacked. Pack them, using
// the packed row offsets array k_ptrs that we created above.
//
// FIXME (mfh 06 Aug 2014) If "Optimize Storage" is false, we
// need to keep around the unpacked row offsets, column
// indices, and values arrays.
// Pack the column indices from unpacked k_lclInds1D_ into
// packed k_inds. We will replace k_lclInds1D_ below.
typedef pack_functor<typename Graph::local_graph_type::entries_type::non_const_type,
typename Graph::local_graph_type::row_map_type>
inds_packer_type;
inds_packer_type indsPacker (k_inds, myGraph_->k_lclInds1D_,
k_ptrs, curRowOffsets);
Kokkos::parallel_for (lclNumRows, indsPacker);
// Pack the values from unpacked k_values1D_ into packed
// k_vals. We will replace k_values1D_ below.
typedef pack_functor<values_type, row_map_type> vals_packer_type;
vals_packer_type valsPacker (k_vals, this->k_values1D_,
k_ptrs, curRowOffsets);
Kokkos::parallel_for (lclNumRows, valsPacker);
TEUCHOS_TEST_FOR_EXCEPTION(
k_ptrs.dimension_0 () == 0, std::logic_error, "Tpetra::CrsMatrix::"
"fillLocalGraphAndMatrix: In StaticProfile \"Optimize Storage\" = "
"true branch, after packing, k_ptrs.dimension_0() = 0. This "
"probably means that k_rowPtrs_ was never allocated.");
if (k_ptrs.dimension_0 () != 0) {
const size_t numOffsets = static_cast<size_t> (k_ptrs.dimension_0 ());
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs(numOffsets - 1)) != k_vals.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In StaticProfile \"Optimize Storage\"=true branch, after packing, "
"k_ptrs(" << (numOffsets-1) << ") = " << k_ptrs(numOffsets-1) <<
" != k_vals.dimension_0() = " << k_vals.dimension_0 () << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs(numOffsets - 1)) != k_inds.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In StaticProfile \"Optimize Storage\"=true branch, after packing, "
"k_ptrs(" << (numOffsets-1) << ") = " << k_ptrs(numOffsets-1) <<
" != k_inds.dimension_0() = " << k_inds.dimension_0 () << ".");
}
}
else { // We don't have to pack, so just set the pointers.
k_ptrs_const = myGraph_->k_rowPtrs_;
k_inds = myGraph_->k_lclInds1D_;
k_vals = this->k_values1D_;
TEUCHOS_TEST_FOR_EXCEPTION(
k_ptrs_const.dimension_0 () == 0, std::logic_error, "Tpetra::CrsMatrix::"
"fillLocalGraphAndMatrix: In StaticProfile \"Optimize Storage\" = "
"false branch, k_ptrs_const.dimension_0() = 0. This probably means that "
"k_rowPtrs_ was never allocated.");
if (k_ptrs_const.dimension_0 () != 0) {
const size_t numOffsets = static_cast<size_t> (k_ptrs_const.dimension_0 ());
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs_const(numOffsets - 1)) != k_vals.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In StaticProfile \"Optimize Storage\" = false branch, "
"k_ptrs_const(" << (numOffsets-1) << ") = " << k_ptrs_const(numOffsets - 1)
<< " != k_vals.dimension_0() = " << k_vals.dimension_0 () << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs_const(numOffsets - 1)) != k_inds.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: "
"In StaticProfile \"Optimize Storage\" = false branch, "
"k_ptrs_const(" << (numOffsets-1) << ") = " << k_ptrs_const(numOffsets - 1)
<< " != k_inds.dimension_0() = " << k_inds.dimension_0 () << ".");
}
}
}
// Extra sanity checks.
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs_const.dimension_0 ()) != lclNumRows + 1,
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: After "
"packing, k_ptrs_const.dimension_0() = " << k_ptrs_const.dimension_0 ()
<< " != lclNumRows+1 = " << (lclNumRows+1) << ".");
if (k_ptrs_const.dimension_0 () != 0) {
const size_t numOffsets = static_cast<size_t> (k_ptrs_const.dimension_0 ());
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs_const(numOffsets - 1)) != k_vals.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: After "
"packing, k_ptrs_const(" << (numOffsets-1) << ") = " << k_ptrs_const(numOffsets-1)
<< " != k_vals.dimension_0() = " << k_vals.dimension_0 () << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs_const(numOffsets - 1)) != k_inds.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalGraphAndMatrix: After "
"packing, k_ptrs_const(" << (numOffsets-1) << ") = " << k_ptrs_const(numOffsets-1)
<< " != k_inds.dimension_0() = " << k_inds.dimension_0 () << ".");
}
// May we ditch the old allocations for the packed (and otherwise
// "optimized") allocations, later in this routine? Optimize
// storage if the graph is not static, or if the graph already has
// optimized storage.
const bool defaultOptStorage =
! isStaticGraph () || staticGraph_->isStorageOptimized ();
const bool requestOptimizedStorage =
(! params.is_null () && params->get ("Optimize Storage", defaultOptStorage)) ||
(params.is_null () && defaultOptStorage);
// The graph has optimized storage when indices are allocated,
// myGraph_->k_numRowEntries_ is empty, and there are more than
// zero rows on this process. It's impossible for the graph to
// have dynamic profile (getProfileType() == DynamicProfile) and
// be optimized (isStorageOptimized()).
if (requestOptimizedStorage) {
// Free the old, unpacked, unoptimized allocations.
// Change the graph from dynamic to static allocation profile
// Free graph data structures that are only needed for 2-D or
// unpacked 1-D storage.
myGraph_->lclInds2D_ = null; // legacy KokkosClassic 2-D storage
myGraph_->k_numRowEntries_ = row_entries_type ();
// Free the matrix's 2-D storage.
this->values2D_ = null;
// Keep the new 1-D packed allocations.
myGraph_->k_rowPtrs_ = k_ptrs_const;
myGraph_->k_lclInds1D_ = k_inds;
this->k_values1D_ = k_vals;
// Storage is packed now, so the number of allocated entries is
// the same as the actual number of entries.
myGraph_->nodeNumAllocated_ = myGraph_->nodeNumEntries_;
// The graph is definitely StaticProfile now, whether or not it
// was before.
myGraph_->pftype_ = StaticProfile;
myGraph_->storageStatus_ = Details::STORAGE_1D_PACKED;
this->storageStatus_ = Details::STORAGE_1D_PACKED;
}
// Make the local graph, using the arrays of row offsets and
// column indices that we built above. The local graph should be
// null, but we delete it first so that any memory can be freed
// before we allocate the new one.
//
// FIXME (mfh 06,28 Aug 2014) It would make more sense for
// Tpetra::CrsGraph to have a protected method that accepts k_inds
// and k_ptrs, and creates the local graph lclGraph_.
myGraph_->lclGraph_ =
typename Graph::local_graph_type (k_inds, k_ptrs_const);
// Make the local matrix, using the local graph and vals array.
lclMatrix_ = local_matrix_type ("Tpetra::CrsMatrix::lclMatrix_",
getNodeNumCols (), k_vals,
myGraph_->lclGraph_);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
fillLocalMatrix (const Teuchos::RCP<Teuchos::ParameterList>& params)
{
using Kokkos::create_mirror_view;
using Teuchos::ArrayRCP;
using Teuchos::Array;
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
typedef LocalOrdinal LO;
typedef typename Graph::t_numRowEntries_ row_entries_type;
typedef typename Graph::local_graph_type::row_map_type row_map_type;
typedef typename row_map_type::non_const_type non_const_row_map_type;
typedef typename local_matrix_type::values_type values_type;
const size_t lclNumRows = getNodeNumRows();
const map_type& rowMap = * (getRowMap ());
RCP<node_type> node = rowMap.getNode ();
// The goals of this routine are first, to allocate and fill
// packed 1-D storage (see below for an explanation) in the vals
// array, and second, to give vals to the local matrix and
// finalize the local matrix. We only need k_ptrs, the packed 1-D
// row offsets, within the scope of this routine, since we're only
// filling the local matrix here (use fillLocalGraphAndMatrix() to
// fill both the graph and the matrix at the same time).
// get data from staticGraph_
ArrayRCP<Array<LO> > lclInds2D = staticGraph_->lclInds2D_;
size_t nodeNumEntries = staticGraph_->nodeNumEntries_;
size_t nodeNumAllocated = staticGraph_->nodeNumAllocated_;
row_map_type k_rowPtrs_ = staticGraph_->lclGraph_.row_map;
row_map_type k_ptrs; // "packed" row offsets array
values_type k_vals; // "packed" values array
// May we ditch the old allocations for the packed (and otherwise
// "optimized") allocations, later in this routine? Request
// optimized storage by default.
bool requestOptimizedStorage = true;
const bool default_OptimizeStorage =
! isStaticGraph () || staticGraph_->isStorageOptimized ();
if (! params.is_null () && ! params->get ("Optimize Storage", default_OptimizeStorage)) {
requestOptimizedStorage = false;
}
// If we're not allowed to change a static graph, then we can't
// change the storage of the matrix, either. This means that if
// the graph's storage isn't already optimized, we can't optimize
// the matrix's storage either. Check and give warning, as
// appropriate.
if (! staticGraph_->isStorageOptimized () && requestOptimizedStorage) {
TPETRA_ABUSE_WARNING(true, std::runtime_error,
"::fillLocalMatrix(): You requested optimized storage by setting the"
"\"Optimize Storage\" flag to \"true\" in the parameter list, or by virtue"
"of default behavior. However, the associated CrsGraph was filled separately"
"and requested not to optimize storage. Therefore, the CrsMatrix cannot"
"optimize storage.");
requestOptimizedStorage = false;
}
// The number of entries in each locally owned row. This is a
// DualView. 2-D storage lives on host and is currently not
// thread-safe for parallel kernels even on host, so we have to
// work sequentially with host storage in that case.
row_entries_type k_numRowEnt = staticGraph_->k_numRowEntries_;
typename row_entries_type::t_host h_numRowEnt = k_numRowEnt.h_view;
if (getProfileType() == DynamicProfile) {
// Pack 2-D storage (DynamicProfile) into 1-D packed storage.
//
// DynamicProfile means that the matrix's values are currently
// stored in a 2-D "unpacked" format, in the array-of-arrays
// values2D_. We allocate 1-D storage and then copy from 2-D
// storage in values2D_ into 1-D storage in k_vals. Since we're
// only allocating the local matrix here, not the local graph,
// we don't need to keep the row offsets array, but we do need
// it here temporarily in order to convert to 1-D storage. (The
// allocStorage() function needs it.) We'll free ptrs later in
// this method.
//
// FIXME (mfh 08 Aug 2014) If we're in this method, then the
// graph should already have packed 1-D storage. Why can't we
// just use the graph's current row offsets array?
// Pack the row offsets into k_ptrs, by doing a sum-scan of
// the array of valid entry counts per row (h_numRowEnt).
//
// Total number of entries in the matrix on the calling
// process. We will compute this in the loop below. It's
// cheap to compute and useful as a sanity check.
size_t lclTotalNumEntries = 0;
// This will be a host view of packed row offsets.
typename non_const_row_map_type::HostMirror h_ptrs;
{
non_const_row_map_type packedRowOffsets ("Tpetra::CrsGraph::ptr",
lclNumRows+1);
//
// FIXME hack until we get parallel_scan in Kokkos
//
h_ptrs = create_mirror_view (packedRowOffsets);
h_ptrs(0) = 0;
for (size_t i = 0; i < lclNumRows; ++i) {
const size_t numEnt = h_numRowEnt(i);
lclTotalNumEntries += numEnt;
h_ptrs(i+1) = h_ptrs(i) + numEnt;
}
Kokkos::deep_copy (packedRowOffsets, h_ptrs);
k_ptrs = packedRowOffsets;
}
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs.dimension_0 ()) != lclNumRows + 1,
std::logic_error, "Tpetra::CrsMatrix::fillLocalMatrix: In "
"DynamicProfile branch, after packing k_ptrs, k_ptrs.dimension_0()"
" = " << k_ptrs.dimension_0 () << " != (lclNumRows+1) = "
<< (lclNumRows+1) << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (h_ptrs.dimension_0 ()) != lclNumRows + 1,
std::logic_error, "Tpetra::CrsMatrix::fillLocalMatrix: In "
"DynamicProfile branch, after packing h_ptrs, h_ptrs.dimension_0()"
" = " << h_ptrs.dimension_0 () << " != (lclNumRows+1) = "
<< (lclNumRows+1) << ".");
// FIXME (mfh 08 Aug 2014) This assumes UVM.
TEUCHOS_TEST_FOR_EXCEPTION(
k_ptrs(lclNumRows) != lclTotalNumEntries, std::logic_error,
"Tpetra::CrsMatrix::fillLocalMatrix: In DynamicProfile branch, "
"after packing k_ptrs, k_ptrs(lclNumRows = " << lclNumRows << ") = " <<
k_ptrs(lclNumRows) << " != total number of entries on the calling "
"process = " << lclTotalNumEntries << ".");
// Allocate the array of packed values.
k_vals = values_type ("Tpetra::CrsMatrix::val", lclTotalNumEntries);
// We need a host view of the above, since 2-D storage lives on host.
typename values_type::HostMirror h_vals = create_mirror_view (k_vals);
// Pack the values on the host.
for (size_t lclRow = 0; lclRow < lclNumRows; ++lclRow) {
const size_t numEnt = h_numRowEnt(lclRow);
std::copy (values2D_[lclRow].begin(),
values2D_[lclRow].begin() + numEnt,
h_vals.ptr_on_device() + h_ptrs(lclRow));
}
// Copy the packed values to the device.
Kokkos::deep_copy (k_vals, h_vals);
// Sanity check of packed row offsets.
if (k_ptrs.dimension_0 () != 0) {
const size_t numOffsets = static_cast<size_t> (k_ptrs.dimension_0 ());
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (k_ptrs(numOffsets-1)) != k_vals.dimension_0 (),
std::logic_error, "Tpetra::CrsMatrix::fillLocalMatrix: "
"In DynamicProfile branch, after packing, k_ptrs(" << (numOffsets-1)
<< ") = " << k_ptrs(numOffsets-1) << " != k_vals.dimension_0() = "
<< k_vals.dimension_0 () << ".");
}
}
else if (getProfileType () == StaticProfile) {
// StaticProfile means that the matrix's values are currently
// stored in a 1-D format. However, this format is "unpacked";
// it doesn't necessarily have the same row offsets as indicated
// by the ptrs array returned by allocRowPtrs. This could
// happen, for example, if the user specified StaticProfile in
// the constructor and fixed the number of matrix entries in
// each row, but didn't fill all those entries.
//
// As above, we don't need to keep the "packed" row offsets
// array ptrs here, but we do need it here temporarily, so we
// have to allocate it. We'll free ptrs later in this method.
//
// Note that this routine checks whether storage has already
// been packed. This is a common case for solution of nonlinear
// PDEs using the finite element method, as long as the
// structure of the sparse matrix does not change between linear
// solves.
if (nodeNumEntries != nodeNumAllocated) {
// We have to pack the 1-D storage, since the user didn't fill
// up all requested storage.
non_const_row_map_type tmpk_ptrs ("Tpetra::CrsGraph::ptr",
lclNumRows+1);
// Total number of entries in the matrix on the calling
// process. We will compute this in the loop below. It's
// cheap to compute and useful as a sanity check.
size_t lclTotalNumEntries = 0;
k_ptrs = tmpk_ptrs;
{
//
// FIXME hack until we get parallel_scan in Kokkos
//
typename non_const_row_map_type::HostMirror h_ptrs =
create_mirror_view (tmpk_ptrs);
h_ptrs(0) = 0;
for (size_t i = 0; i < lclNumRows; ++i) {
const size_t numEnt = h_numRowEnt(i);
lclTotalNumEntries += numEnt;
h_ptrs(i+1) = h_ptrs(i) + numEnt;
}
Kokkos::deep_copy (tmpk_ptrs, h_ptrs);
}
// Allocate the "packed" values array.
// It has exactly the right number of entries.
k_vals = values_type ("Tpetra::CrsMatrix::val", lclTotalNumEntries);
// Pack k_values1D_ into k_vals. We will replace k_values1D_ below.
typedef pack_functor<values_type, row_map_type> packer_type;
packer_type valsPacker (k_vals, k_values1D_, tmpk_ptrs, k_rowPtrs_);
Kokkos::parallel_for (lclNumRows, valsPacker);
}
else { // We don't have to pack, so just set the pointer.
k_vals = k_values1D_;
}
}
// May we ditch the old allocations for the packed one?
if (requestOptimizedStorage) {
// The user requested optimized storage, so we can dump the
// unpacked 2-D and 1-D storage, and keep the packed storage.
values2D_ = null;
k_values1D_ = k_vals;
this->storageStatus_ = Details::STORAGE_1D_PACKED;
}
// Build the local sparse matrix object. At this point, the local
// matrix certainly has a column Map. Remember that the local
// matrix's number of columns comes from the column Map, not the
// domain Map.
lclMatrix_ = local_matrix_type ("Tpetra::CrsMatrix::lclMatrix_",
getColMap ()->getNodeNumElements (),
k_vals,
staticGraph_->getLocalGraph ());
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
insertLocalValues (const LocalOrdinal localRow,
const Teuchos::ArrayView<const LocalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
using Teuchos::toString;
using std::endl;
const char tfecfFuncName[] = "insertLocalValues";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! isFillActive (), std::runtime_error,
": Fill is not active. After calling fillComplete, you must call "
"resumeFill before you may insert entries into the matrix again.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(isStaticGraph (), std::runtime_error,
" cannot insert indices with static graph; use replaceLocalValues() instead.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(myGraph_->isGloballyIndexed(),
std::runtime_error, ": graph indices are global; use insertGlobalValues().");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! hasColMap (), std::runtime_error,
" cannot insert local indices without a column map.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(values.size() != indices.size(),
std::runtime_error, ": values.size() must equal indices.size().");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! getRowMap()->isNodeLocalElement(localRow), std::runtime_error,
": Local row index " << localRow << " does not belong to this process.");
if (! myGraph_->indicesAreAllocated ()) {
try {
allocateValues (LocalIndices, GraphNotYetAllocated);
}
catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix::insertLocalValues: "
"allocateValues(LocalIndices,GraphNotYetAllocated) threw an "
"exception: " << e.what ());
}
}
const size_t numEntriesToAdd = static_cast<size_t> (indices.size ());
#ifdef HAVE_TPETRA_DEBUG
// In a debug build, if the matrix has a column Map, test whether
// any of the given column indices are not in the column Map.
// Keep track of the invalid column indices so we can tell the
// user about them.
if (hasColMap ()) {
const map_type& colMap = * (getColMap ());
Array<LocalOrdinal> badColInds;
bool allInColMap = true;
for (size_t k = 0; k < numEntriesToAdd; ++k) {
if (! colMap.isNodeLocalElement (indices[k])) {
allInColMap = false;
badColInds.push_back (indices[k]);
}
}
if (! allInColMap) {
std::ostringstream os;
os << "Tpetra::CrsMatrix::insertLocalValues: You attempted to insert "
"entries in owned row " << localRow << ", at the following column "
"indices: " << toString (indices) << "." << endl;
os << "Of those, the following indices are not in the column Map on "
"this process: " << toString (badColInds) << "." << endl << "Since "
"the matrix has a column Map already, it is invalid to insert "
"entries at those locations.";
TEUCHOS_TEST_FOR_EXCEPTION(! allInColMap, std::invalid_argument, os.str ());
}
}
#endif // HAVE_TPETRA_DEBUG
#ifdef HAVE_TPETRA_DEBUG
RowInfo rowInfo;
try {
rowInfo = myGraph_->getRowInfo (localRow);
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix::insertLocalValues: "
"myGraph_->getRowInfo threw an exception: " << e.what ());
}
#else
RowInfo rowInfo = myGraph_->getRowInfo (localRow);
#endif // HAVE_TPETRA_DEBUG
const size_t curNumEntries = rowInfo.numEntries;
const size_t newNumEntries = curNumEntries + numEntriesToAdd;
if (newNumEntries > rowInfo.allocSize) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
getProfileType() == StaticProfile, std::runtime_error,
": new indices exceed statically allocated graph structure.");
// Make space for the new matrix entries.
try {
rowInfo = myGraph_->template updateLocalAllocAndValues<impl_scalar_type> (rowInfo,
newNumEntries,
values2D_[localRow]);
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix::insertLocalValues: "
"myGraph_->updateGlobalAllocAndValues threw an exception: "
<< e.what ());
}
}
typename Graph::SLocalGlobalViews indsView;
indsView.linds = indices;
#ifdef HAVE_TPETRA_DEBUG
ArrayView<impl_scalar_type> valsView;
try {
valsView = this->getViewNonConst (rowInfo);
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix::insertLocalValues: "
"getViewNonConst threw an exception: " << e.what ());
}
#else
ArrayView<impl_scalar_type> valsView = this->getViewNonConst (rowInfo);
#endif // HAVE_TPETRA_DEBUG
ArrayView<const impl_scalar_type> valsIn =
av_reinterpret_cast<const impl_scalar_type> (values);
try {
myGraph_->template insertIndicesAndValues<impl_scalar_type> (rowInfo, indsView,
valsView, valsIn,
LocalIndices,
LocalIndices);
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix::insertLocalValues: "
"myGraph_->insertIndicesAndValues threw an exception: "
<< e.what ());
}
#ifdef HAVE_TPETRA_DEBUG
const size_t chkNewNumEntries = myGraph_->getNumEntriesInLocalRow (localRow);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
chkNewNumEntries != newNumEntries, std::logic_error,
": The row should have " << newNumEntries << " entries after insert, but "
"instead has " << chkNewNumEntries << ". Please report this bug to the "
"Tpetra developers.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! isLocallyIndexed(), std::logic_error,
": At end of insertLocalValues(), this CrsMatrix is not locally indexed. "
"Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
insertLocalValuesFiltered (const LocalOrdinal localRow,
const Teuchos::ArrayView<const LocalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
const char tfecfFuncName[] = "insertLocalValues: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! isFillActive (), std::runtime_error,
"Requires that fill is active.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(isStaticGraph (), std::runtime_error,
"Cannot insert indices with static graph; use replaceLocalValues() instead.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(myGraph_->isGloballyIndexed(),
std::runtime_error, "Graph indices are global; use insertGlobalValues().");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! hasColMap (), std::runtime_error, "The matrix has no column Map yet, "
"so you cannot insert local indices. If you created the matrix without "
"a column Map (or without a fill-complete graph), you must call "
"fillComplete to create the column Map, before you may work with local "
"indices.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
values.size () != indices.size (), std::runtime_error, "values.size() = "
<< values.size () << " != indices.size() = " << indices.size ()<< ".");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! getRowMap()->isNodeLocalElement (localRow), std::runtime_error,
"Local row index " << localRow << " does not belong to this process.");
if (! myGraph_->indicesAreAllocated ()) {
allocateValues (LocalIndices, GraphNotYetAllocated);
}
// Use the graph to filter incoming entries whose column indices
// aren't in the column Map.
Array<LocalOrdinal> f_inds (indices);
ArrayView<const impl_scalar_type> valsIn =
av_reinterpret_cast<const impl_scalar_type> (values);
Array<impl_scalar_type> f_vals (valsIn);
const size_t numFilteredEntries =
myGraph_->template filterLocalIndicesAndValues<impl_scalar_type> (f_inds (),
f_vals ());
if (numFilteredEntries > 0) {
RowInfo rowInfo = myGraph_->getRowInfo (localRow);
const size_t curNumEntries = rowInfo.numEntries;
const size_t newNumEntries = curNumEntries + numFilteredEntries;
if (newNumEntries > rowInfo.allocSize) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
getProfileType () == StaticProfile, std::runtime_error,
": new indices exceed statically allocated graph structure. "
"newNumEntries (" << newNumEntries << " > rowInfo.allocSize ("
<< rowInfo.allocSize << ").");
// Make space for the new matrix entries.
rowInfo =
myGraph_->template updateLocalAllocAndValues<impl_scalar_type> (rowInfo,
newNumEntries,
values2D_[localRow]);
}
typename Graph::SLocalGlobalViews inds_view;
inds_view.linds = f_inds (0, numFilteredEntries);
myGraph_->template insertIndicesAndValues<impl_scalar_type> (rowInfo, inds_view,
this->getViewNonConst (rowInfo),
f_vals, LocalIndices,
LocalIndices);
#ifdef HAVE_TPETRA_DEBUG
const size_t chkNewNumEntries = myGraph_->getNumEntriesInLocalRow (localRow);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(chkNewNumEntries != newNumEntries,
std::logic_error, ": Internal logic error. Please contact Tpetra team.");
#endif // HAVE_TPETRA_DEBUG
}
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! isLocallyIndexed(), std::logic_error,
": At end of insertLocalValues(), this CrsMatrix is not locally indexed. "
"Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
insertGlobalValues (const GlobalOrdinal globalRow,
const Teuchos::ArrayView<const GlobalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
using Teuchos::toString;
using std::endl;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef typename ArrayView<const GO>::size_type size_type;
const char tfecfFuncName[] = "insertGlobalValues: ";
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
values.size () != indices.size (), std::runtime_error,
"values.size() = " << values.size() << " != indices.size() = "
<< indices.size() << ".");
#endif // HAVE_TPETRA_DEBUG
const LO localRow = getRowMap ()->getLocalElement (globalRow);
if (localRow == OTL::invalid ()) { // globalRow _not_ owned by calling process
insertNonownedGlobalValues (globalRow, indices, values);
}
else { // globalRow _is_ owned by calling process
if (this->isStaticGraph ()) {
// Uh oh! Not allowed to insert into owned rows in that case.
std::ostringstream err;
const int myRank = getRowMap ()->getComm ()->getRank ();
const int numProcs = getRowMap ()->getComm ()->getSize ();
err << "The matrix was constructed with a constant (\"static\") graph, "
"yet the given global row index " << globalRow << " is in the row "
"Map on the calling process (with rank " << myRank << ", of " <<
numProcs << " process(es)). In this case, you may not insert new "
"entries into rows owned by the calling process.";
if (! getRowMap ()->isNodeGlobalElement (globalRow)) {
err << " Furthermore, GID->LID conversion with the row Map claims that "
"the global row index is owned on the calling process, yet "
"getRowMap()->isNodeGlobalElement(globalRow) returns false. That's"
" weird! This might indicate a Map bug. Please report this to the"
" Tpetra developers.";
}
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
this->isStaticGraph (), std::runtime_error, err.str ());
}
if (! myGraph_->indicesAreAllocated ()) {
try {
allocateValues (GlobalIndices, GraphNotYetAllocated);
}
catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "Tpetra::CrsMatrix::insertGlobalValues: "
"allocateValues(GlobalIndices,GraphNotYetAllocated) threw an "
"exception: " << e.what ());
}
}
const size_type numEntriesToInsert = indices.size ();
// If the matrix has a column Map, check at this point whether
// the column indices belong to the column Map.
//
// FIXME (mfh 16 May 2013) We may want to consider deferring the
// test to the CrsGraph method, since it may have to do this
// anyway.
if (hasColMap ()) {
const map_type& colMap = * (getColMap ());
// In a debug build, keep track of the nonowned ("bad") column
// indices, so that we can display them in the exception
// message. In a release build, just ditch the loop early if
// we encounter a nonowned column index.
#ifdef HAVE_TPETRA_DEBUG
Array<GO> badColInds;
#endif // HAVE_TPETRA_DEBUG
bool allInColMap = true;
for (size_type k = 0; k < numEntriesToInsert; ++k) {
if (! colMap.isNodeGlobalElement (indices[k])) {
allInColMap = false;
#ifdef HAVE_TPETRA_DEBUG
badColInds.push_back (indices[k]);
#else
break;
#endif // HAVE_TPETRA_DEBUG
}
}
if (! allInColMap) {
std::ostringstream os;
os << "You attempted to insert entries in owned row " << globalRow
<< ", at the following column indices: " << toString (indices)
<< "." << endl;
#ifdef HAVE_TPETRA_DEBUG
os << "Of those, the following indices are not in the column Map on "
"this process: " << toString (badColInds) << "." << endl << "Since "
"the matrix has a column Map already, it is invalid to insert "
"entries at those locations.";
#else
os << "At least one of those indices is not in the column Map on this "
"process." << endl << "It is invalid to insert into columns not in "
"the column Map on the process that owns the row.";
#endif // HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! allInColMap, std::invalid_argument, os.str ());
}
}
typename Graph::SLocalGlobalViews inds_view;
ArrayView<const impl_scalar_type> vals_view;
inds_view.ginds = indices;
vals_view = av_reinterpret_cast<const impl_scalar_type> (values);
#ifdef HAVE_TPETRA_DEBUG
RowInfo rowInfo;
try {
rowInfo = myGraph_->getRowInfo (localRow);
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "myGraph_->getRowInfo(localRow=" << localRow
<< ") threw an exception: " << e.what ());
}
#else
RowInfo rowInfo = myGraph_->getRowInfo (localRow);
#endif // HAVE_TPETRA_DEBUG
const size_t curNumEntries = rowInfo.numEntries;
const size_t newNumEntries =
curNumEntries + static_cast<size_t> (numEntriesToInsert);
if (newNumEntries > rowInfo.allocSize) {
TEUCHOS_TEST_FOR_EXCEPTION(
getProfileType () == StaticProfile && newNumEntries > rowInfo.allocSize,
std::runtime_error, "Tpetra::CrsMatrix::insertGlobalValues: new "
"indices exceed statically allocated graph structure. curNumEntries"
" (" << curNumEntries << ") + numEntriesToInsert (" <<
numEntriesToInsert << ") > allocSize (" << rowInfo.allocSize << ").");
// Update allocation only as much as necessary
try {
rowInfo =
myGraph_->template updateGlobalAllocAndValues<impl_scalar_type> (rowInfo,
newNumEntries,
values2D_[localRow]);
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "myGraph_->updateGlobalAllocAndValues"
"(...) threw an exception: " << e.what ());
}
}
try {
if (isGloballyIndexed ()) {
// lg=GlobalIndices, I=GlobalIndices means the method calls
// getGlobalViewNonConst() and does direct copying, which
// should be reasonably fast.
myGraph_->template insertIndicesAndValues<impl_scalar_type> (rowInfo, inds_view,
this->getViewNonConst (rowInfo),
vals_view,
GlobalIndices, GlobalIndices);
}
else {
// lg=GlobalIndices, I=LocalIndices means the method calls
// the Map's getLocalElement() method once per entry to
// insert. This may be slow.
myGraph_->template insertIndicesAndValues<impl_scalar_type> (rowInfo, inds_view,
this->getViewNonConst (rowInfo),
vals_view,
GlobalIndices, LocalIndices);
}
}
catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, "myGraph_->insertIndicesAndValues(...) "
"threw an exception: " << e.what ());
}
#ifdef HAVE_TPETRA_DEBUG
const size_t chkNewNumEntries = myGraph_->getNumEntriesInLocalRow (localRow);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(chkNewNumEntries != newNumEntries,
std::logic_error, ": There should be a total of " << newNumEntries
<< " entries in the row, but the graph now reports " << chkNewNumEntries
<< " entries. Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
insertGlobalValuesFiltered (const GlobalOrdinal globalRow,
const Teuchos::ArrayView<const GlobalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef impl_scalar_type ST;
const char tfecfFuncName[] = "insertGlobalValuesFiltered: ";
// mfh 14 Dec 2012: Defer test for static graph until we know that
// globalRow is in the row Map. If it's not in the row Map, it
// doesn't matter whether or not the graph is static; the data
// just get stashed for later use by globalAssemble().
//
// TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
// isStaticGraph(), std::runtime_error,
// ": matrix was constructed with static graph. Cannot insert new entries.");
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
values.size () != indices.size (), std::runtime_error,
"values.size() = " << values.size() << " != indices.size() = "
<< indices.size() << ".");
#endif // HAVE_TPETRA_DEBUG
ArrayView<const ST> valsIn = av_reinterpret_cast<const ST> (values);
const LO lrow = getRowMap ()->getLocalElement (globalRow);
if (lrow != Teuchos::OrdinalTraits<LO>::invalid ()) { // globalRow is in our row Map.
// If the matrix has a static graph, this process is now allowed
// to insert into rows it owns.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
this->isStaticGraph (), std::runtime_error,
"The matrix was constructed with a static graph. In that case, "
"it is forbidden to insert new entries into rows owned by the "
"calling process.");
if (! myGraph_->indicesAreAllocated ()) {
allocateValues (GlobalIndices, GraphNotYetAllocated);
}
typename Graph::SLocalGlobalViews inds_view;
ArrayView<const ST> vals_view;
// We have to declare these Arrays here rather than in the
// hasColMap() if branch, so that views to them will remain
// valid for the whole scope.
Array<GO> filtered_indices;
Array<ST> filtered_values;
if (hasColMap ()) { // We have a column Map.
// Use column Map to filter the indices and corresponding
// values, so that we only insert entries into columns we own.
filtered_indices.assign (indices.begin (), indices.end ());
filtered_values.assign (valsIn.begin (), valsIn.end ());
const size_t numFilteredEntries =
myGraph_->template filterGlobalIndicesAndValues<ST> (filtered_indices (),
filtered_values ());
inds_view.ginds = filtered_indices (0, numFilteredEntries);
vals_view = filtered_values (0, numFilteredEntries);
}
else { // we don't have a column Map.
inds_view.ginds = indices;
vals_view = valsIn;
}
const size_t numFilteredEntries = vals_view.size ();
// add the new indices and values
if (numFilteredEntries > 0) {
RowInfo rowInfo = myGraph_->getRowInfo (lrow);
const size_t curNumEntries = rowInfo.numEntries;
const size_t newNumEntries = curNumEntries + numFilteredEntries;
if (newNumEntries > rowInfo.allocSize) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
getProfileType () == StaticProfile, std::runtime_error,
"New indices exceed statically allocated graph structure.");
// Update allocation only as much as necessary
rowInfo = myGraph_->template updateGlobalAllocAndValues<ST> (rowInfo,
newNumEntries,
values2D_[lrow]);
}
if (isGloballyIndexed ()) {
// lg=GlobalIndices, I=GlobalIndices means the method calls
// getGlobalViewNonConst() and does direct copying, which
// should be reasonably fast.
myGraph_->template insertIndicesAndValues<ST> (rowInfo, inds_view,
this->getViewNonConst (rowInfo),
vals_view,
GlobalIndices, GlobalIndices);
}
else {
// lg=GlobalIndices, I=LocalIndices means the method calls
// the Map's getLocalElement() method once per entry to
// insert. This may be slow.
myGraph_->template insertIndicesAndValues<ST> (rowInfo, inds_view,
this->getViewNonConst (rowInfo),
vals_view,
GlobalIndices, LocalIndices);
}
#ifdef HAVE_TPETRA_DEBUG
{
const size_t chkNewNumEntries = myGraph_->getNumEntriesInLocalRow (lrow);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(chkNewNumEntries != newNumEntries,
std::logic_error, ": There should be a total of " << newNumEntries
<< " entries in the row, but the graph now reports " << chkNewNumEntries
<< " entries. Please report this bug to the Tpetra developers.");
}
#endif // HAVE_TPETRA_DEBUG
}
}
else { // The calling process doesn't own the given row.
insertNonownedGlobalValues (globalRow, indices, values);
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
LocalOrdinal
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
replaceLocalValues (const LocalOrdinal localRow,
const Teuchos::ArrayView<const LocalOrdinal> &indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef impl_scalar_type ST;
// project2nd is a binary function that returns its second
// argument. This replaces entries in the given row with their
// corresponding entry of values.
typedef Tpetra::project2nd<ST, ST> f_type;
typedef typename ArrayView<GO>::size_type size_type;
ArrayView<const ST> valsIn = av_reinterpret_cast<const ST> (values);
if (! isFillActive ()) {
// Fill must be active in order to call this method.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
else if (! this->hasColMap ()) {
// There is no such thing as local column indices without a column Map.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
else if (values.size () != indices.size ()) {
// The sizes of values and indices must match.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
const bool isLocalRow = getRowMap ()->isNodeLocalElement (localRow);
if (! isLocalRow) {
// The calling process does not own this row, so it is not
// allowed to modify its values.
//
// FIXME (mfh 02 Jan 2015) replaceGlobalValues returns invalid
// in this case.
return static_cast<LO> (0);
}
if (indices.size () == 0) {
return static_cast<LO> (0);
}
else {
RowInfo rowInfo = staticGraph_->getRowInfo (localRow);
ArrayView<ST> curVals = this->getViewNonConst (rowInfo);
if (isLocallyIndexed ()) {
return staticGraph_->template transformLocalValues<ST, f_type> (rowInfo,
curVals,
indices,
valsIn,
f_type ());
}
else if (isGloballyIndexed ()) {
// Convert the given local indices to global indices.
//
// FIXME (mfh 27 Jun 2014) Why can't we ask the graph to do
// that? It could do the conversions in place, so that we
// wouldn't need temporary storage.
const map_type& colMap = * (this->getColMap ());
const size_type numInds = indices.size ();
// mfh 27 Jun 2014: Some of the given local indices might be
// invalid. That's OK, though, since the graph ignores them
// and their corresponding values in transformGlobalValues.
// Thus, we don't have to count how many indices are valid.
// We do so just as a sanity check.
Array<GO> gblInds (numInds);
size_type numValid = 0; // sanity check count of # valid indices
for (size_type k = 0; k < numInds; ++k) {
const GO gid = colMap.getGlobalElement (indices[k]);
gblInds[k] = gid;
if (gid != Teuchos::OrdinalTraits<GO>::invalid ()) {
++numValid; // sanity check count of # valid indices
}
}
const LO numXformed =
staticGraph_->template transformGlobalValues<ST, f_type> (rowInfo,
curVals, // target
gblInds,
valsIn, // source
f_type ());
if (static_cast<size_type> (numXformed) != numValid) {
return Teuchos::OrdinalTraits<LO>::invalid ();
} else {
return numXformed;
}
}
// NOTE (mfh 26 Jun 2014) In the current version of CrsMatrix,
// it's possible for a matrix (or graph) to be neither locally
// nor globally indexed on a process. This means that the graph
// or matrix has no entries on that process. Epetra also works
// like this. It's related to lazy allocation (on first
// insertion, not at graph / matrix construction). Lazy
// allocation will go away because it is not thread scalable.
return static_cast<LO> (0);
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
LocalOrdinal
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
replaceGlobalValues (GlobalOrdinal globalRow,
const Teuchos::ArrayView<const GlobalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef impl_scalar_type ST;
// project2nd is a binary function that returns its second
// argument. This replaces entries in the given row with their
// corresponding entry of values.
typedef Tpetra::project2nd<ST, ST> f_type;
typedef typename ArrayView<GO>::size_type size_type;
ArrayView<const ST> valsIn = av_reinterpret_cast<const ST> (values);
if (! isFillActive ()) {
// Fill must be active in order to call this method.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
else if (values.size () != indices.size ()) {
// The sizes of values and indices must match.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
const LO lrow = this->getRowMap ()->getLocalElement (globalRow);
if (lrow == Teuchos::OrdinalTraits<LO>::invalid ()) {
// The calling process does not own this row, so it is not
// allowed to modify its values.
//
// FIXME (mfh 02 Jan 2015) replaceLocalValues returns 0 in this case.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
if (staticGraph_.is_null ()) {
return Teuchos::OrdinalTraits<LO>::invalid ();
}
const crs_graph_type& graph = *staticGraph_;
RowInfo rowInfo = graph.getRowInfo (lrow);
if (indices.size () == 0) {
return static_cast<LO> (0);
}
else {
ArrayView<ST> curVals = this->getViewNonConst (rowInfo);
if (isLocallyIndexed ()) {
// Convert the given global indices to local indices.
//
// FIXME (mfh 08 Jul 2014) Why can't we ask the graph to do
// that? It could do the conversions in place, so that we
// wouldn't need temporary storage.
const map_type& colMap = * (this->getColMap ());
const size_type numInds = indices.size ();
Array<LO> lclInds (numInds);
for (size_type k = 0; k < numInds; ++k) {
// There is no need to filter out indices not in the
// column Map. Those that aren't will be mapped to
// invalid(), which the graph's transformGlobalValues()
// will filter out (but not count in its return value).
lclInds[k] = colMap.getLocalElement (indices[k]);
}
return graph.template transformLocalValues<ST, f_type> (rowInfo,
curVals,
lclInds (),
valsIn,
f_type ());
}
else if (isGloballyIndexed ()) {
return graph.template transformGlobalValues<ST, f_type> (rowInfo,
curVals,
indices,
valsIn,
f_type ());
}
else {
// If the graph is neither locally nor globally indexed on
// the calling process, that means that the calling process
// can't possibly have any entries in the owned row. Thus,
// there are no entries to transform, so we return zero.
return static_cast<LO> (0);
}
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
LocalOrdinal
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
sumIntoGlobalValues (const GlobalOrdinal globalRow,
const Teuchos::ArrayView<const GlobalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef impl_scalar_type ST;
typedef std::plus<Scalar> f_type;
typedef typename ArrayView<GO>::size_type size_type;
ArrayView<const ST> valsIn = av_reinterpret_cast<const ST> (values);
if (! isFillActive ()) {
// Fill must be active in order to call this method.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
else if (values.size () != indices.size ()) {
// The sizes of values and indices must match.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
const LO lrow = this->getRowMap ()->getLocalElement (globalRow);
if (lrow == Teuchos::OrdinalTraits<LO>::invalid ()) {
// globalRow is not in the row Map, so stash the given entries
// away in a separate data structure. globalAssemble() (called
// during fillComplete()) will exchange that data and sum it in
// using sumIntoGlobalValues().
this->insertNonownedGlobalValues (globalRow, indices, values);
// FIXME (mfh 08 Jul 2014) It's not clear what to return here,
// since we won't know whether the given indices were valid
// until globalAssemble (called in fillComplete) is called.
// That's why insertNonownedGlobalValues doesn't return
// anything. Just for consistency, I'll return the number of
// entries that the user gave us.
return static_cast<LO> (indices.size ());
}
if (staticGraph_.is_null ()) {
return Teuchos::OrdinalTraits<LO>::invalid ();
}
const crs_graph_type& graph = *staticGraph_;
RowInfo rowInfo = graph.getRowInfo (lrow);
if (indices.size () == 0) {
return static_cast<LO> (0);
}
else {
ArrayView<ST> curVals = this->getViewNonConst (rowInfo);
if (isLocallyIndexed ()) {
// Convert the given global indices to local indices.
//
// FIXME (mfh 08 Jul 2014) Why can't we ask the graph to do
// that? It could do the conversions in place, so that we
// wouldn't need temporary storage.
const map_type& colMap = * (this->getColMap ());
const size_type numInds = indices.size ();
Array<LO> lclInds (numInds);
for (size_type k = 0; k < numInds; ++k) {
// There is no need to filter out indices not in the
// column Map. Those that aren't will be mapped to
// invalid(), which the graph's transformGlobalValues()
// will filter out (but not count in its return value).
lclInds[k] = colMap.getLocalElement (indices[k]);
}
return graph.template transformLocalValues<ST, f_type> (rowInfo,
curVals,
lclInds (),
valsIn,
f_type ());
}
else if (isGloballyIndexed ()) {
return graph.template transformGlobalValues<ST, f_type> (rowInfo,
curVals,
indices,
valsIn,
f_type ());
}
else {
// If the graph is neither locally nor globally indexed on
// the calling process, that means that the calling process
// can't possibly have any entries in the owned row. Thus,
// there are no entries to transform, so we return zero.
return static_cast<LO> (0);
}
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
LocalOrdinal
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
sumIntoLocalValues (const LocalOrdinal localRow,
const Teuchos::ArrayView<const LocalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef impl_scalar_type ST;
typedef std::plus<Scalar> f_type;
typedef typename ArrayView<GO>::size_type size_type;
ArrayView<const ST> valsIn = av_reinterpret_cast<const ST> (values);
if (! isFillActive ()) {
// Fill must be active in order to call this method.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
else if (! this->hasColMap ()) {
// There is no such thing as local column indices without a column Map.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
else if (values.size () != indices.size ()) {
// The sizes of values and indices must match.
return Teuchos::OrdinalTraits<LO>::invalid ();
}
const bool isLocalRow = getRowMap ()->isNodeLocalElement (localRow);
if (! isLocalRow) {
// The calling process doesn't own the local row, so we can't
// insert into it.
return static_cast<LO> (0);
}
if (indices.size () == 0) {
return static_cast<LO> (0);
}
else {
RowInfo rowInfo = staticGraph_->getRowInfo (localRow);
ArrayView<ST> curVals = this->getViewNonConst (rowInfo);
if (isLocallyIndexed ()) {
return staticGraph_->template transformLocalValues<ST, f_type> (rowInfo,
curVals,
indices,
valsIn,
f_type ());
}
else if (isGloballyIndexed ()) {
// Convert the given local indices to global indices.
//
// FIXME (mfh 27 Jun 2014) Why can't we ask the graph to do
// that? It could do the conversions in place, so that we
// wouldn't need temporary storage.
const map_type& colMap = * (this->getColMap ());
const size_type numInds = indices.size ();
// mfh 27 Jun 2014: Some of the given local indices might be
// invalid. That's OK, though, since the graph ignores them
// and their corresponding values in transformGlobalValues.
// Thus, we don't have to count how many indices are valid.
// We do so just as a sanity check.
Array<GO> gblInds (numInds);
size_type numValid = 0; // sanity check count of # valid indices
for (size_type k = 0; k < numInds; ++k) {
const GO gid = colMap.getGlobalElement (indices[k]);
gblInds[k] = gid;
if (gid != Teuchos::OrdinalTraits<GO>::invalid ()) {
++numValid; // sanity check count of # valid indices
}
}
const LO numXformed =
staticGraph_->template transformGlobalValues<ST, f_type> (rowInfo,
curVals, // target
gblInds,
valsIn, // source
f_type ());
if (static_cast<size_type> (numXformed) != numValid) {
return Teuchos::OrdinalTraits<LO>::invalid ();
} else {
return numXformed;
}
}
// NOTE (mfh 26 Jun 2014) In the current version of CrsMatrix,
// it's possible for a matrix (or graph) to be neither locally
// nor globally indexed on a process. This means that the graph
// or matrix has no entries on that process. Epetra also works
// like this. It's related to lazy allocation (on first
// insertion, not at graph / matrix construction). Lazy
// allocation will go away because it is not thread scalable.
return static_cast<LO> (0);
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::ArrayView<const typename CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::impl_scalar_type>
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getView (RowInfo rowinfo) const
{
using Kokkos::MemoryUnmanaged;
using Kokkos::View;
using Teuchos::ArrayView;
typedef impl_scalar_type ST;
typedef std::pair<size_t, size_t> range_type;
if (k_values1D_.dimension_0 () != 0 && rowinfo.allocSize > 0) {
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION(
rowinfo.offset1D + rowinfo.allocSize > k_values1D_.dimension_0 (),
std::range_error, "Tpetra::CrsMatrix::getView: Invalid access "
"to 1-D storage of values." << std::endl << "rowinfo.offset1D (" <<
rowinfo.offset1D << ") + rowinfo.allocSize (" << rowinfo.allocSize <<
") > k_values1D_.dimension_0() (" << k_values1D_.dimension_0 () << ").");
#endif // HAVE_TPETRA_DEBUG
range_type range (rowinfo.offset1D, rowinfo.offset1D + rowinfo.allocSize);
typedef View<const ST*, execution_space, MemoryUnmanaged> subview_type;
subview_type sv = Kokkos::subview (k_values1D_, range);
const ST* const sv_raw = (rowinfo.allocSize == 0) ? NULL : sv.ptr_on_device ();
return ArrayView<const ST> (sv_raw, rowinfo.allocSize);
}
else if (values2D_ != null) {
return values2D_[rowinfo.localRow] ();
}
else {
return ArrayView<impl_scalar_type> ();
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::ArrayView<typename CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::impl_scalar_type>
CrsMatrix<Scalar, LocalOrdinal,GlobalOrdinal, Node, classic>::
getViewNonConst (RowInfo rowinfo)
{
return Teuchos::av_const_cast<impl_scalar_type> (this->getView (rowinfo));
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getLocalRowCopy (LocalOrdinal localRow,
const Teuchos::ArrayView<LocalOrdinal>& indices,
const Teuchos::ArrayView<Scalar>& values,
size_t& numEntries) const
{
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
TEUCHOS_TEST_FOR_EXCEPTION(
isGloballyIndexed () && ! hasColMap (), std::runtime_error,
"Tpetra::CrsMatrix::getLocalRowCopy: The matrix is globally indexed and "
"does not have a column Map yet. That means we don't have local indices "
"for columns yet, so it doesn't make sense to call this method. If the "
"matrix doesn't have a column Map yet, you should call fillComplete on "
"it first.");
TEUCHOS_TEST_FOR_EXCEPTION(
! staticGraph_->hasRowInfo (), std::runtime_error,
"Tpetra::CrsMatrix::getLocalRowCopy: The graph's row information was "
"deleted at fillComplete().");
if (! this->getRowMap ()->isNodeLocalElement (localRow)) {
// The calling process owns no entries in this row.
numEntries = 0;
return;
}
const RowInfo rowinfo = staticGraph_->getRowInfo (localRow);
const size_t theNumEntries = rowinfo.numEntries;
TEUCHOS_TEST_FOR_EXCEPTION(
static_cast<size_t> (indices.size ()) < theNumEntries ||
static_cast<size_t> (values.size ()) < theNumEntries,
std::runtime_error,
"Tpetra::CrsMatrix::getLocalRowCopy: The given row " << localRow
<< " has " << theNumEntries << " entries. One or both of the given "
"ArrayViews are not long enough to store that many entries. indices "
"can store " << indices.size() << " entries and values can store "
<< values.size() << " entries.");
numEntries = theNumEntries;
if (staticGraph_->isLocallyIndexed ()) {
ArrayView<const LO> indrowview = staticGraph_->getLocalView (rowinfo);
ArrayView<const Scalar> valrowview =
av_reinterpret_cast<const Scalar> (this->getView (rowinfo));
std::copy (indrowview.begin (), indrowview.begin () + numEntries, indices.begin ());
std::copy (valrowview.begin (), valrowview.begin () + numEntries, values.begin ());
}
else if (staticGraph_->isGloballyIndexed ()) {
ArrayView<const GO> indrowview = staticGraph_->getGlobalView (rowinfo);
ArrayView<const Scalar> valrowview =
av_reinterpret_cast<const Scalar> (this->getView (rowinfo));
std::copy (valrowview.begin (), valrowview.begin () + numEntries, values.begin ());
const map_type& colMap = * (this->getColMap ());
for (size_t j=0; j < numEntries; ++j) {
indices[j] = colMap.getLocalElement (indrowview[j]);
}
}
else {
numEntries = 0;
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalRowCopy (GlobalOrdinal globalRow,
const Teuchos::ArrayView<GlobalOrdinal>& indices,
const Teuchos::ArrayView<Scalar>& values,
size_t& numEntries) const
{
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
const char tfecfFuncName[] = "getGlobalRowCopy: ";
const LocalOrdinal lrow = getRowMap ()->getLocalElement (globalRow);
if (lrow == OTL::invalid ()) {
// The calling process owns no entries in this row.
numEntries = 0;
return;
}
const RowInfo rowinfo = staticGraph_->getRowInfo (lrow);
const size_t theNumEntries = rowinfo.numEntries;
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
static_cast<size_t> (indices.size ()) < theNumEntries ||
static_cast<size_t> (values.size ()) < theNumEntries,
std::runtime_error,
"The given row " << globalRow << ", corresponding to local row " << lrow
<< ", has " << theNumEntries << " entries. One or both of the given "
"ArrayView input arguments are not long enough to store that many "
"entries. indices.size() = " << indices.size() << ", values.size() = "
<< values.size () << ", but the number of entries in the row is "
<< theNumEntries << ".");
// Don't "commit" the value until we know that the input arrays are valid.
numEntries = theNumEntries;
if (staticGraph_->isGloballyIndexed ()) {
ArrayView<const GO> indrowview = staticGraph_->getGlobalView (rowinfo);
ArrayView<const Scalar> valrowview =
av_reinterpret_cast<const Scalar> (this->getView (rowinfo));
std::copy (indrowview.begin (), indrowview.begin () + numEntries, indices.begin ());
std::copy (valrowview.begin (), valrowview.begin () + numEntries, values.begin ());
}
else if (staticGraph_->isLocallyIndexed ()) {
ArrayView<const LO> indrowview = staticGraph_->getLocalView(rowinfo);
ArrayView<const Scalar> valrowview =
av_reinterpret_cast<const Scalar> (this->getView (rowinfo));
std::copy (valrowview.begin (), valrowview.begin () + numEntries, values.begin ());
for (size_t j = 0; j < numEntries; ++j) {
indices[j] = getColMap ()->getGlobalElement (indrowview[j]);
}
}
else {
#ifdef HAVE_TPETRA_DEBUG
// should have fallen in one of the above if indices are allocated
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
staticGraph_->indicesAreAllocated (), std::logic_error,
"Internal logic error. Please contact Tpetra team.");
#endif // HAVE_TPETRA_DEBUG
numEntries = 0;
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getLocalRowView (LocalOrdinal localRow,
Teuchos::ArrayView<const LocalOrdinal>& indices,
Teuchos::ArrayView<const Scalar>& values) const
{
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
const char tfecfFuncName[] = "getLocalRowView: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
isGloballyIndexed (), std::runtime_error, "The matrix currently stores "
"its indices as global indices, so you cannot get a view with local "
"column indices. If the matrix has a column Map, you may call "
"getLocalRowCopy() to get local column indices; otherwise, you may get "
"a view with global column indices by calling getGlobalRowCopy().");
indices = Teuchos::null;
values = Teuchos::null;
#ifdef HAVE_TPETRA_DEBUG
size_t numEntries = 0;
#endif // HAVE_TPETRA_DEBUG
if (getRowMap ()->isNodeLocalElement (localRow)) {
const RowInfo rowinfo = staticGraph_->getRowInfo (localRow);
#ifdef HAVE_TPETRA_DEBUG
numEntries = rowinfo.numEntries;
#endif // HAVE_TPETRA_DEBUG
if (rowinfo.numEntries > 0) {
ArrayView<const LO> indTmp = staticGraph_->getLocalView (rowinfo);
ArrayView<const Scalar> valTmp =
av_reinterpret_cast<const Scalar> (this->getView (rowinfo));
indices = indTmp (0, rowinfo.numEntries);
values = valTmp (0, rowinfo.numEntries);
}
}
#ifdef HAVE_TPETRA_DEBUG
const char suffix[] = ". This should never happen. Please report this "
"bug to the Tpetra developers.";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
static_cast<size_t>(indices.size ()) != static_cast<size_t>(values.size ()), std::logic_error,
"At the end of this method, for local row " << localRow << ", "
"indices.size() = " << indices.size () << " != values.size () = "
<< values.size () << suffix);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
static_cast<size_t>(indices.size ()) != static_cast<size_t>(numEntries), std::logic_error,
"At the end of this method, for local row " << localRow << ", "
"indices.size() = " << indices.size () << " != numEntries = "
<< numEntries << suffix);
const size_t expectedNumEntries = this->getNumEntriesInLocalRow (localRow);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
numEntries != expectedNumEntries, std::logic_error,
"At the end of this method, for local row " << localRow << ", numEntries"
" = " << numEntries << " != getNumEntriesInLocalRow(localRow)"
" = "<< expectedNumEntries << suffix);
#endif // HAVE_TPETRA_DEBUG
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getGlobalRowView (GlobalOrdinal globalRow,
Teuchos::ArrayView<const GlobalOrdinal>& indices,
Teuchos::ArrayView<const Scalar>& values) const
{
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef GlobalOrdinal GO;
const char tfecfFuncName[] = "getGlobalRowView: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
isLocallyIndexed (), std::runtime_error,
"The matrix is locally indexed, so we cannot return a view of the row "
"with global column indices. Use getGlobalRowCopy() instead.");
indices = Teuchos::null;
values = Teuchos::null;
const LocalOrdinal lrow = getRowMap ()->getLocalElement (globalRow);
if (lrow != Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
// getRowInfo() requires a local row index, whether or not
// storage has been optimized.
const RowInfo rowinfo = staticGraph_->getRowInfo(lrow);
if (rowinfo.numEntries > 0) {
ArrayView<const GO> indTmp = staticGraph_->getGlobalView (rowinfo);
ArrayView<const Scalar> valTmp =
av_reinterpret_cast<const Scalar> (this->getView (rowinfo));
indices = indTmp (0, rowinfo.numEntries);
values = valTmp (0, rowinfo.numEntries);
}
}
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
static_cast<size_t> (indices.size ()) != this->getNumEntriesInGlobalRow (globalRow) ||
indices.size () != values.size (),
std::logic_error,
"Violated stated post-conditions. Please contact Tpetra team.");
#endif // HAVE_TPETRA_DEBUG
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
scale (const Scalar& alpha)
{
typedef LocalOrdinal LO;
typedef Kokkos::SparseRowView<local_matrix_type> row_view_type;
typedef typename Teuchos::Array<Scalar>::size_type size_type;
const char tfecfFuncName[] = "scale: ";
const impl_scalar_type theAlpha = static_cast<impl_scalar_type> (alpha);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillActive (), std::runtime_error,
"Fill must be active before you may call this method. "
"Please call resumeFill() to make fill active.");
const size_t nlrs = staticGraph_->getNodeNumRows ();
const size_t numAlloc = staticGraph_->getNodeAllocationSize ();
const size_t numEntries = staticGraph_->getNodeNumEntries ();
if (! staticGraph_->indicesAreAllocated () || nlrs == 0 ||
numAlloc == 0 || numEntries == 0) {
// do nothing
}
else {
if (staticGraph_->getProfileType () == StaticProfile) {
const LO lclNumRows = lclMatrix_.numRows ();
for (LO lclRow = 0; lclRow < lclNumRows; ++lclRow) {
row_view_type row_i = lclMatrix_.template row<typename row_view_type::size_type> (lclRow);
for (LO k = 0; k < row_i.length; ++k) {
// FIXME (mfh 02 Jan 2015) This assumes CUDA UVM.
row_i.value (k) *= theAlpha;
}
}
}
else if (staticGraph_->getProfileType () == DynamicProfile) {
for (size_t row = 0; row < nlrs; ++row) {
const size_type numEnt = getNumEntriesInLocalRow (row);
Teuchos::ArrayView<impl_scalar_type> rowVals = values2D_[row] ();
for (size_type k = 0; k < numEnt; ++k) {
rowVals[k] *= theAlpha;
}
}
}
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
setAllToScalar (const Scalar& alpha)
{
const char tfecfFuncName[] = "setAllToScalar: ";
const impl_scalar_type theAlpha = static_cast<impl_scalar_type> (alpha);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillActive (), std::runtime_error,
"Fill must be active before you may call this method. "
"Please call resumeFill() to make fill active.");
// replace all values in the matrix
// it is easiest to replace all allocated values, instead of replacing only the ones with valid entries
// however, if there are no valid entries, we can short-circuit
// furthermore, if the values aren't allocated, we can short-circuit (no entry have been inserted so far)
const size_t nlrs = staticGraph_->getNodeNumRows(),
numAlloc = staticGraph_->getNodeAllocationSize(),
numEntries = staticGraph_->getNodeNumEntries();
if (! staticGraph_->indicesAreAllocated () || numAlloc == 0 || numEntries == 0) {
// do nothing
}
else {
const ProfileType profType = staticGraph_->getProfileType ();
if (profType == StaticProfile) {
// FIXME (mfh 24 Dec 2014) Once CrsMatrix implements DualView
// semantics, this would be the place to mark memory as
// modified.
typedef typename local_matrix_type::values_type values_type;
Kokkos::Impl::ViewFill<values_type> (k_values1D_, theAlpha);
}
else if (profType == DynamicProfile) {
for (size_t row = 0; row < nlrs; ++row) {
std::fill (values2D_[row].begin (), values2D_[row].end (), theAlpha);
}
}
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
setAllValues (const typename local_matrix_type::row_map_type& rowPointers,
const typename local_graph_type::entries_type::non_const_type& columnIndices,
const typename local_matrix_type::values_type& values)
{
const char tfecfFuncName[] = "setAllValues";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
columnIndices.size () != values.size (), std::runtime_error,
": columnIndices and values must have the same size. columnIndices.size() = "
<< columnIndices.size () << " != values.size() = " << values.size () << ".");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
myGraph_.is_null (), std::runtime_error, ": myGraph_ must not be null.");
try {
myGraph_->setAllIndices (rowPointers, columnIndices);
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::runtime_error, ": Caught exception while calling myGraph_->"
"setAllIndices(): " << e.what ());
}
k_values1D_ = values;
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
setAllValues (const Teuchos::ArrayRCP<size_t>& rowPointers,
const Teuchos::ArrayRCP<LocalOrdinal>& columnIndices,
const Teuchos::ArrayRCP<Scalar>& values)
{
const char tfecfFuncName[] = "setAllValues: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
columnIndices.size () != values.size (), std::runtime_error,
"columnIndices.size() = " << columnIndices.size () << " != "
"values.size() = " << values.size () << ".");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
myGraph_.is_null (), std::runtime_error, "myGraph_ must not be null.");
try {
myGraph_->setAllIndices (rowPointers, columnIndices);
}
catch (std::exception &e) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::runtime_error, "Caught exception while calling myGraph_->"
"setAllIndices(): " << e.what ());
}
Teuchos::ArrayRCP<impl_scalar_type> vals =
Teuchos::arcp_reinterpret_cast<impl_scalar_type> (values);
k_values1D_ = Kokkos::Compat::getKokkosViewDeepCopy<device_type> (vals ());
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getLocalDiagOffsets (Teuchos::ArrayRCP<size_t>& offsets) const
{
using Teuchos::ArrayRCP;
using Teuchos::ArrayView;
const char tfecfFuncName[] = "getLocalDiagOffsets";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! hasColMap (), std::runtime_error,
": This method requires that the matrix have a column Map.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
staticGraph_.is_null (), std::runtime_error,
": This method requires that the matrix have a graph.");
const map_type& rowMap = * (this->getRowMap ());
const map_type& colMap = * (this->getColMap ());
const size_t myNumRows = getNodeNumRows ();
if (static_cast<size_t> (offsets.size ()) != myNumRows) {
offsets.resize (static_cast<size_t> (myNumRows));
}
#ifdef HAVE_TPETRA_DEBUG
bool allRowMapDiagEntriesInColMap = true;
bool allDiagEntriesFound = true;
#endif // HAVE_TPETRA_DEBUG
for (size_t r = 0; r < myNumRows; ++r) {
const GlobalOrdinal rgid = rowMap.getGlobalElement (r);
const LocalOrdinal rlid = colMap.getLocalElement (rgid);
#ifdef HAVE_TPETRA_DEBUG
if (rlid == Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
allRowMapDiagEntriesInColMap = false;
}
#endif // HAVE_TPETRA_DEBUG
if (rlid != Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
RowInfo rowinfo = staticGraph_->getRowInfo (r);
if (rowinfo.numEntries > 0) {
offsets[r] = staticGraph_->findLocalIndex (rowinfo, rlid);
}
else {
offsets[r] = Teuchos::OrdinalTraits<size_t>::invalid ();
#ifdef HAVE_TPETRA_DEBUG
allDiagEntriesFound = false;
#endif // HAVE_TPETRA_DEBUG
}
}
}
#ifdef HAVE_TPETRA_DEBUG
using Teuchos::reduceAll;
using std::endl;
const bool localSuccess =
allRowMapDiagEntriesInColMap && allDiagEntriesFound;
int localResults[3];
localResults[0] = allRowMapDiagEntriesInColMap ? 1 : 0;
localResults[1] = allDiagEntriesFound ? 1 : 0;
// min-all-reduce will compute least rank of all the processes
// that didn't succeed.
localResults[2] =
! localSuccess ? getComm ()->getRank () : getComm ()->getSize ();
int globalResults[3];
globalResults[0] = 0;
globalResults[1] = 0;
globalResults[2] = 0;
reduceAll<int, int> (* (getComm ()), Teuchos::REDUCE_MIN,
3, localResults, globalResults);
if (globalResults[0] == 0 || globalResults[1] == 0) {
std::ostringstream os; // build error message
const bool both =
globalResults[0] == 0 && globalResults[1] == 0;
os << ": At least one process (including Process " << globalResults[2]
<< ") had the following issue" << (both ? "s" : "") << ":" << endl;
if (globalResults[0] == 0) {
os << " - The column Map does not contain at least one diagonal entry "
"of the matrix." << endl;
}
if (globalResults[1] == 0) {
os << " - There is a row on that / those process(es) that does not "
"contain a diagonal entry." << endl;
}
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(true, std::runtime_error, os.str());
}
#endif // HAVE_TPETRA_DEBUG
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getLocalDiagCopy (Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& dvec) const
{
using Teuchos::ArrayRCP;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
const char tfecfFuncName[] = "getLocalDiagCopy: ";
typedef Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> vec_type;
typedef typename vec_type::dual_view_type dual_view_type;
typedef typename dual_view_type::host_mirror_space::execution_space host_execution_space;
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! hasColMap (), std::runtime_error,
"This method requires that the matrix have a column Map.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
staticGraph_.is_null (), std::runtime_error,
"This method requires that the matrix have a graph.");
const map_type& rowMap = * (this->getRowMap ());
const map_type& colMap = * (this->getColMap ());
#ifdef HAVE_TPETRA_DEBUG
// isCompatible() requires an all-reduce, and thus this check
// should only be done in debug mode.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! dvec.getMap ()->isCompatible (rowMap), std::runtime_error,
": The input Vector's Map must be compatible with the CrsMatrix's row "
"Map. You may check this by using Map's isCompatible method: "
"dvec.getMap ()->isCompatible (A.getRowMap ());");
#endif // HAVE_TPETRA_DEBUG
// For now, we fill the Vector on the host and sync to device.
// Later, we may write a parallel kernel that works entirely on
// device.
dual_view_type lclVec = dvec.getDualView ();
lclVec.template modify<host_execution_space> ();
typedef typename dual_view_type::t_host host_view_type;
host_view_type lclVecHost = lclVec.h_view;
// 1-D subview of lclVecHost. All the "typename" stuff ensures
// that we get the same layout and memory traits as the original
// 2-D view.
typedef typename Kokkos::View<impl_scalar_type*,
typename host_view_type::array_layout,
typename host_view_type::device_type,
typename host_view_type::memory_traits>
host_view_1d_type;
host_view_1d_type lclVecHost1d =
Kokkos::subview (lclVecHost, Kokkos::ALL (), 0);
// Find the diagonal entries and put them in lclVecHost1d.
const size_t myNumRows = getNodeNumRows ();
for (size_t r = 0; r < myNumRows; ++r) {
lclVecHost1d(r) = STS::zero (); // default value if no diag entry
const GlobalOrdinal rgid = rowMap.getGlobalElement (r);
const LocalOrdinal rlid = colMap.getLocalElement (rgid);
if (rlid != Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
RowInfo rowinfo = staticGraph_->getRowInfo (r);
if (rowinfo.numEntries > 0) {
const size_t j = staticGraph_->findLocalIndex (rowinfo, rlid);
if (j != Teuchos::OrdinalTraits<size_t>::invalid ()) {
// NOTE (mfh 02 Jan 2015) This technically does not assume
// UVM, since getView and getViewNonConst are supposed to
// return views of host data.
ArrayView<const impl_scalar_type> view = this->getView (rowinfo);
lclVecHost1d(r) = view[j];
}
}
}
}
lclVec.template sync<execution_space> (); // sync changes back to device
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getLocalDiagCopy (Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& diag,
const Teuchos::ArrayView<const size_t>& offsets) const
{
using Teuchos::ArrayRCP;
using Teuchos::ArrayView;
typedef Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> vec_type;
typedef typename vec_type::dual_view_type dual_view_type;
typedef typename dual_view_type::host_mirror_space::execution_space host_execution_space;
#ifdef HAVE_TPETRA_DEBUG
const char tfecfFuncName[] = "getLocalDiagCopy: ";
const map_type& rowMap = * (this->getRowMap ());
// isCompatible() requires an all-reduce, and thus this check
// should only be done in debug mode.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! diag.getMap ()->isCompatible (rowMap), std::runtime_error,
"The input Vector's Map must be compatible with (in the sense of Map::"
"isCompatible) the CrsMatrix's row Map.");
#endif // HAVE_TPETRA_DEBUG
// For now, we fill the Vector on the host and sync to device.
// Later, we may write a parallel kernel that works entirely on
// device.
dual_view_type lclVec = diag.getDualView ();
lclVec.template modify<host_execution_space> ();
typedef typename dual_view_type::t_host host_view_type;
host_view_type lclVecHost = lclVec.h_view;
// 1-D subview of lclVecHost. All the "typename" stuff ensures
// that we get the same layout and memory traits as the original
// 2-D view.
typedef typename Kokkos::View<impl_scalar_type*,
typename host_view_type::array_layout,
typename host_view_type::device_type,
typename host_view_type::memory_traits>
host_view_1d_type;
host_view_1d_type lclVecHost1d =
Kokkos::subview (lclVecHost, Kokkos::ALL (), 0);
// Find the diagonal entries and put them in lclVecHost1d.
const size_t myNumRows = getNodeNumRows ();
for (size_t i = 0; i < myNumRows; ++i) {
lclVecHost1d(i) = STS::zero (); // default value if no diag entry
if (offsets[i] != Teuchos::OrdinalTraits<size_t>::invalid ()) {
ArrayView<const LocalOrdinal> ind;
ArrayView<const Scalar> val;
// NOTE (mfh 02 Jan 2015) This technically does not assume
// UVM, since the get{Global,Local}RowView methods are
// supposed to return views of host data.
this->getLocalRowView (i, ind, val);
lclVecHost1d(i) = static_cast<impl_scalar_type> (val[offsets[i]]);
}
}
lclVec.template sync<execution_space> (); // sync changes back to device
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
leftScale (const Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& x)
{
using Teuchos::ArrayRCP;
using Teuchos::ArrayView;
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcpFromRef;
typedef Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> vec_type;
const char tfecfFuncName[] = "leftScale";
// FIXME (mfh 06 Aug 2014) This doesn't make sense. The matrix
// should only be modified when it is not fill complete.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillComplete (), std::runtime_error,
": matrix must be fill complete.");
RCP<const vec_type> xp;
if (getRangeMap ()->isSameAs (* (x.getMap ()))){
// Take from Epetra: If we have a non-trivial exporter, we must
// import elements that are permuted or are on other processors.
// (We will use the exporter to perform the import ("reverse
// mode").)
if (getCrsGraph ()->getExporter () != null) {
RCP<vec_type> tempVec = rcp (new vec_type (getRowMap ()));
tempVec->doImport (x, * (getCrsGraph ()->getExporter ()), INSERT);
xp = tempVec;
}
else {
xp = rcpFromRef (x);
}
}
else if (getRowMap ()->isSameAs (* (x.getMap ()))) {
xp = rcpFromRef (x);
}
else {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(true, std::invalid_argument, ": The "
"input scaling vector x's Map must be the same as either the row Map or "
"the range Map of the CrsMatrix.");
}
ArrayRCP<const Scalar> vectorVals = xp->getData (0);
ArrayView<impl_scalar_type> rowValues = null;
const size_t lclNumRows = this->getNodeNumRows ();
for (size_t i = 0; i < lclNumRows; ++i) {
const RowInfo rowinfo = staticGraph_->getRowInfo (static_cast<LocalOrdinal> (i));
rowValues = this->getViewNonConst (rowinfo);
const impl_scalar_type scaleValue = static_cast<impl_scalar_type> (vectorVals[i]);
for (size_t j = 0; j < rowinfo.numEntries; ++j) {
rowValues[j] *= scaleValue;
}
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
rightScale (const Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& x)
{
using Teuchos::ArrayRCP;
using Teuchos::ArrayView;
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcpFromRef;
typedef Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> vec_type;
const char tfecfFuncName[] = "rightScale: ";
// FIXME (mfh 06 Aug 2014) This doesn't make sense. The matrix
// should only be modified when it is not fill complete.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillComplete (), std::runtime_error, "Matrix must be fill complete.");
RCP<const vec_type> xp;
if (getDomainMap ()->isSameAs (* (x.getMap ()))) {
// Take from Epetra: If we have a non-trivial exporter, we must
// import elements that are permuted or are on other processors.
// (We will use the exporter to perform the import.)
if (getCrsGraph ()->getImporter () != null) {
RCP<vec_type> tempVec = rcp (new vec_type (getColMap ()));
tempVec->doImport (x, * (getCrsGraph ()->getImporter ()), INSERT);
xp = tempVec;
}
else {
xp = rcpFromRef (x);
}
}
else if (getRowMap ()->isSameAs (* (x.getMap ()))) {
xp = rcpFromRef (x);
} else {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::runtime_error, "The vector x must have the same Map as "
"either the row Map or the range Map.");
}
ArrayRCP<const Scalar> vectorVals = xp->getData (0);
ArrayView<impl_scalar_type> rowValues = null;
const size_t lclNumRows = this->getNodeNumRows ();
for (size_t i = 0; i < lclNumRows; ++i) {
const RowInfo rowinfo = staticGraph_->getRowInfo (static_cast<LocalOrdinal> (i));
rowValues = this->getViewNonConst (rowinfo);
ArrayView<const LocalOrdinal> colInds;
getCrsGraph ()->getLocalRowView (static_cast<LocalOrdinal> (i), colInds);
for (size_t j = 0; j < rowinfo.numEntries; ++j) {
rowValues[j] *= static_cast<impl_scalar_type> (vectorVals[colInds[j]]);
}
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
typename CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::mag_type
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getFrobeniusNorm () const
{
using Teuchos::outArg;
using Teuchos::REDUCE_SUM;
using Teuchos::reduceAll;
typedef typename Teuchos::ArrayRCP<const impl_scalar_type>::size_type size_type;
// FIXME (mfh 05 Aug 2014) Write a thread-parallel kernel for the
// local part of this computation. It could make sense to put
// this operation in the Kokkos::CrsMatrix.
// check the cache first
mag_type frobNorm = frobNorm_;
if (frobNorm == -STM::one ()) {
mag_type mySum = STM::zero ();
if (getNodeNumEntries() > 0) {
if (isStorageOptimized ()) {
// "Optimized" storage is packed storage. That means we can
// iterate in one pass through the 1-D values array.
const size_type numEntries =
static_cast<size_type> (getNodeNumEntries ());
for (size_type k = 0; k < numEntries; ++k) {
// FIXME (mfh 05 Aug 2014) This assumes UVM.
const impl_scalar_type val = k_values1D_(k);
// Note (etp 06 Jan 2015) We need abs() here for composite types
// (in general, if mag_type is on the left-hand-side, we need
// abs() on the right-hand-side)
const mag_type val_abs = STS::abs (val);
mySum += val_abs * val_abs;
}
}
else {
const size_t numRows = getNodeNumRows ();
for (size_t r = 0; r < numRows; ++r) {
RowInfo rowInfo = myGraph_->getRowInfo (r);
const size_type numEntries =
static_cast<size_type> (rowInfo.numEntries);
ArrayView<const impl_scalar_type> A_r =
this->getView (rowInfo).view (0, numEntries);
for (size_type k = 0; k < numEntries; ++k) {
const impl_scalar_type val = A_r[k];
const mag_type val_abs = STS::abs (val);
mySum += val_abs * val_abs;
}
}
}
}
mag_type totalSum = STM::zero ();
reduceAll<int, mag_type> (* (getComm ()), REDUCE_SUM,
mySum, outArg (totalSum));
frobNorm = STM::sqrt (totalSum);
}
if (isFillComplete ()) {
// Only cache the result if the matrix is fill complete.
// Otherwise, the values might still change. resumeFill clears
// the cache.
frobNorm_ = frobNorm;
}
return frobNorm;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
replaceColMap (const Teuchos::RCP<const map_type>& newColMap)
{
const char tfecfFuncName[] = "replaceColMap: ";
// FIXME (mfh 06 Aug 2014) What if the graph is locally indexed?
// Then replacing the column Map might mean that we need to
// reindex the column indices.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
myGraph_.is_null (), std::runtime_error,
"This method does not work if the matrix has a const graph. The whole "
"idea of a const graph is that you are not allowed to change it, but "
"this method necessarily must modify the graph, since the graph owns "
"the matrix's column Map.");
myGraph_->replaceColMap (newColMap);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
reindexColumns (crs_graph_type* const graph,
const Teuchos::RCP<const map_type>& newColMap,
const Teuchos::RCP<const import_type>& newImport,
const bool sortEachRow)
{
const char tfecfFuncName[] = "reindexColumns: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
graph == NULL && myGraph_.is_null (), std::invalid_argument,
"The input graph is NULL, but the matrix does not own its graph.");
crs_graph_type& theGraph = (graph == NULL) ? *myGraph_ : *graph;
const bool sortGraph = false; // we'll sort graph & matrix together below
theGraph.reindexColumns (newColMap, newImport, sortGraph);
if (sortEachRow && theGraph.isLocallyIndexed () && ! theGraph.isSorted ()) {
// We can't just call sortEntries() here, because that fails if
// the matrix has a const graph. We want to use the given graph
// in that case.
const size_t lclNumRows = theGraph.getNodeNumRows ();
for (size_t row = 0; row < lclNumRows; ++row) {
RowInfo rowInfo = theGraph.getRowInfo (row);
Teuchos::ArrayView<impl_scalar_type> rv = this->getViewNonConst (rowInfo);
theGraph.template sortRowIndicesAndValues<impl_scalar_type> (rowInfo, rv);
}
theGraph.indicesAreSorted_ = true;
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
replaceDomainMapAndImporter (const Teuchos::RCP<const map_type>& newDomainMap,
Teuchos::RCP<const import_type>& newImporter)
{
const char tfecfFuncName[] = "replaceDomainMapAndImporter: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
myGraph_.is_null (), std::runtime_error,
"This method does not work if the matrix has a const graph. The whole "
"idea of a const graph is that you are not allowed to change it, but this"
" method necessarily must modify the graph, since the graph owns the "
"matrix's domain Map and Import objects.");
myGraph_->replaceDomainMapAndImporter (newDomainMap, newImporter);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
insertNonownedGlobalValues (const GlobalOrdinal globalRow,
const Teuchos::ArrayView<const GlobalOrdinal>& indices,
const Teuchos::ArrayView<const Scalar>& values)
{
using Teuchos::Array;
typedef GlobalOrdinal GO;
typedef typename Array<GO>::size_type size_type;
const size_type numToInsert = indices.size ();
// Add the new data to the list of nonlocals.
// This creates the arrays if they don't exist yet.
std::pair<Array<GO>, Array<Scalar> >& curRow = nonlocals_[globalRow];
Array<GO>& curRowInds = curRow.first;
Array<Scalar>& curRowVals = curRow.second;
const size_type newCapacity = curRowInds.size () + numToInsert;
curRowInds.reserve (newCapacity);
curRowVals.reserve (newCapacity);
for (size_type k = 0; k < numToInsert; ++k) {
curRowInds.push_back (indices[k]);
curRowVals.push_back (values[k]);
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
globalAssemble ()
{
using Teuchos::arcp;
using Teuchos::Array;
using Teuchos::ArrayRCP;
using Teuchos::ArrayView;
using Teuchos::CommRequest;
using Teuchos::gatherAll;
using Teuchos::isend;
using Teuchos::ireceive;
using Teuchos::null;
using Teuchos::outArg;
using Teuchos::RCP;
using Teuchos::rcpFromRef;
using Teuchos::REDUCE_MAX;
using Teuchos::reduceAll;
using Teuchos::SerialDenseMatrix;
using Teuchos::tuple;
using Teuchos::waitAll;
using std::make_pair;
using std::pair;
typedef GlobalOrdinal GO;
typedef typename Array<GO>::size_type size_type;
// nonlocals_ contains the entries stored by previous calls to
// insertGlobalValues() for nonowned rows.
typedef std::map<GO, pair<Array<GO>, Array<Scalar> > > nonlocals_map_type;
typedef typename nonlocals_map_type::const_iterator nonlocals_iter_type;
const char tfecfFuncName[] = "globalAssemble";
const Teuchos::Comm<int>& comm = * (getComm ());
const int numImages = comm.getSize ();
const int myImageID = comm.getRank ();
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillActive (), std::runtime_error, ": requires that fill is active.");
// Determine (via a global all-reduce) if any processes have
// nonlocal entries to share. This is necessary even if the
// matrix has a static graph, because insertGlobalValues allows
// nonlocal entries in that case.
size_t MyNonlocals = static_cast<size_t> (nonlocals_.size ());
size_t MaxGlobalNonlocals = 0;
reduceAll<int, size_t> (comm, REDUCE_MAX, MyNonlocals,
outArg (MaxGlobalNonlocals));
if (MaxGlobalNonlocals == 0) {
return; // no entries to share
}
// FIXME (mfh 14 Dec 2012) The code below reimplements an Export
// operation. It would be better just to use an Export. See
// Comment #34 in discussion of Bug 5782.
//
// mfh 24 Feb 2014: On the other hand, this is not technically an
// Export, since the row Map might not necessarily be one-to-one.
// compute a list of NLRs from nonlocals_ and use it to compute:
// IdsAndRows: a vector of (id,row) pairs
// NLR2Id: a map from NLR to the Id that owns it
// globalNeighbors: a global graph of connectivity between images:
// globalNeighbors(i,j) indicates that j sends to i
// sendIDs: a list of all images I send to
// recvIDs: a list of all images I receive from (constructed later)
Array<pair<int,GlobalOrdinal> > IdsAndRows;
std::map<GlobalOrdinal,int> NLR2Id;
SerialDenseMatrix<int,char> globalNeighbors;
Array<int> sendIDs, recvIDs;
{
// Construct the set of all nonowned rows encountered by this
// process in insertGlobalValues() or sumIntoGlobalValues().
std::set<GlobalOrdinal> setOfRows;
for (nonlocals_iter_type iter = nonlocals_.begin ();
iter != nonlocals_.end (); ++iter) {
setOfRows.insert (iter->first);
}
// Copy the resulting set of nonowned rows into an Array.
Array<GlobalOrdinal> NLRs (setOfRows.size ());
std::copy (setOfRows.begin (), setOfRows.end (), NLRs.begin ());
// get a list of ImageIDs for the non-local rows (NLRs)
Array<int> NLRIds (NLRs.size ());
{
const LookupStatus stat =
getRowMap ()->getRemoteIndexList (NLRs (), NLRIds ());
const int lclerr = (stat == IDNotPresent ? 1 : 0);
int gblerr;
reduceAll<int, int> (comm, REDUCE_MAX, lclerr, outArg (gblerr));
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
gblerr, std::runtime_error, ": non-local entries correspond to "
"invalid rows.");
}
// build up a list of neighbors, as well as a map between NLRs and Ids
// localNeighbors[i] != 0 iff I have data to send to image i
// put NLRs,Ids into an array of pairs
IdsAndRows.reserve (NLRs.size ());
Array<char> localNeighbors (numImages, 0);
typename Array<GO>::const_iterator nlr;
typename Array<int>::const_iterator id;
for (nlr = NLRs.begin (), id = NLRIds.begin ();
nlr != NLRs.end (); ++nlr, ++id) {
NLR2Id[*nlr] = *id;
localNeighbors[*id] = 1;
IdsAndRows.push_back (make_pair (*id, *nlr));
}
for (int j = 0; j < numImages; ++j) {
if (localNeighbors[j]) {
sendIDs.push_back (j);
}
}
// sort IdsAndRows, by Ids first, then rows
std::sort (IdsAndRows.begin (), IdsAndRows.end ());
// gather from other nodes to form the full graph
//
// FIXME (mfh 24 Feb 2014) Ugh, this is awful!!! It's making a
// P x P matrix which is the full graph of process connectivity.
// Neither Export nor Import does this! It would probably be
// more efficient to do the following:
//
// 1. Form the one-to-one version of the row Map, tgtMap
// 2. Form the (possibly overlapping) Map srcMap, with the
// global row indices which are the keys of nonlocals_ on
// each process
// 3. Construct an Export from srcMap to tgtMap
// 4. Execute the Export with Tpetra::ADD
globalNeighbors.shapeUninitialized (numImages, numImages);
gatherAll (comm, numImages, localNeighbors.getRawPtr (),
numImages*numImages, globalNeighbors.values ());
// globalNeighbors at this point contains (on all images) the
// connectivity between the images.
// globalNeighbors(i,j) != 0 means that j sends to i/that i receives from j
}
//////////////////////////////////////////////////////////////////////////////////////
// FIGURE OUT WHO IS SENDING TO WHOM AND HOW MUCH
// DO THIS IN THE PROCESS OF PACKING ALL OUTGOING DATA ACCORDING TO DESTINATION ID
//////////////////////////////////////////////////////////////////////////////////////
// loop over all columns to know from which images I can expect to receive something
for (int j=0; j<numImages; ++j) {
if (globalNeighbors (myImageID, j)) {
recvIDs.push_back (j);
}
}
const size_t numRecvs = recvIDs.size ();
// we know how many we're sending to already
// form a contiguous list of all data to be sent
// track the number of entries for each ID
Array<Details::CrsIJV<GlobalOrdinal, Scalar> > IJVSendBuffer;
Array<size_t> sendSizes (sendIDs.size(), 0);
size_t numSends = 0;
for (typename Array<pair<int, GlobalOrdinal> >::const_iterator IdAndRow = IdsAndRows.begin();
IdAndRow != IdsAndRows.end(); ++IdAndRow)
{
const int id = IdAndRow->first;
const GO row = IdAndRow->second;
// have we advanced to a new send?
if (sendIDs[numSends] != id) {
numSends++;
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
sendIDs[numSends] != id, std::logic_error,
": internal logic error. Contact Tpetra team.");
}
// copy data for row into contiguous storage
pair<Array<GO>, Array<Scalar> >& nonlocalsRow = nonlocals_[row];
ArrayView<const GO> nonlocalsRow_colInds = nonlocalsRow.first ();
ArrayView<const Scalar> nonlocalsRow_values = nonlocalsRow.second ();
const size_type numNonlocalsRow = nonlocalsRow_colInds.size ();
for (size_type k = 0; k < numNonlocalsRow; ++k) {
const Scalar val = nonlocalsRow_values[k];
const GO col = nonlocalsRow_colInds[k];
IJVSendBuffer.push_back (Details::CrsIJV<GO, Scalar> (row, col, val));
sendSizes[numSends]++;
}
}
if (IdsAndRows.size () > 0) {
numSends++; // one last increment, to make it a count instead of an index
}
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
static_cast<size_type> (numSends) != sendIDs.size(),
std::logic_error, ": internal logic error. Contact Tpetra team.");
// don't need this data anymore
// clear it before we start allocating a bunch of new memory
nonlocals_.clear ();
//////////////////////////////////////////////////////////////////////////////////////
// TRANSMIT SIZE INFO BETWEEN SENDERS AND RECEIVERS
//////////////////////////////////////////////////////////////////////////////////////
// perform non-blocking sends: send sizes to our recipients
Array<RCP<CommRequest<int> > > sendRequests;
for (size_t s = 0; s < numSends ; ++s) {
// we'll fake the memory management, because all communication will be local to this method and the scope of our data
sendRequests.push_back (isend<int, size_t> (comm, rcpFromRef (sendSizes[s]), sendIDs[s]));
}
// perform non-blocking receives: receive sizes from our senders
Array<RCP<CommRequest<int> > > recvRequests;
Array<size_t> recvSizes (numRecvs);
for (size_t r = 0; r < numRecvs; ++r) {
// we'll fake the memory management, because all communication
// will be local to this method and the scope of our data
recvRequests.push_back (ireceive<int, size_t> (comm, rcpFromRef (recvSizes[r]), recvIDs[r]));
}
// wait on all
if (! sendRequests.empty ()) {
waitAll (comm, sendRequests ());
}
if (! recvRequests.empty ()) {
waitAll (comm, recvRequests ());
}
comm.barrier ();
sendRequests.clear ();
recvRequests.clear ();
////////////////////////////////////////////////////////////////////////////////////
// NOW SEND/RECEIVE ALL ROW DATA
////////////////////////////////////////////////////////////////////////////////////
// from the size info, build the ArrayViews into IJVSendBuffer
Array<ArrayView<Details::CrsIJV<GO, Scalar> > > sendBuffers (numSends, null);
{
size_t cur = 0;
for (size_t s=0; s<numSends; ++s) {
sendBuffers[s] = IJVSendBuffer (cur, sendSizes[s]);
cur += sendSizes[s];
}
}
// perform non-blocking sends
for (size_t s = 0; s < numSends; ++s) {
// we'll fake the memory management, because all communication
// will be local to this method and the scope of our data
ArrayRCP<Details::CrsIJV<GO, Scalar> > tmparcp =
arcp (sendBuffers[s].getRawPtr (), 0, sendBuffers[s].size (), false);
sendRequests.push_back (isend<int, Details::CrsIJV<GlobalOrdinal,Scalar> > (comm, tmparcp, sendIDs[s]));
}
// calculate amount of storage needed for receives
// setup pointers for the receives as well
size_t totalRecvSize = std::accumulate (recvSizes.begin (), recvSizes.end (), 0);
Array<Details::CrsIJV<GO, Scalar> > IJVRecvBuffer (totalRecvSize);
// from the size info, build the ArrayViews into IJVRecvBuffer
Array<ArrayView<Details::CrsIJV<GO, Scalar> > > recvBuffers (numRecvs, null);
{
size_t cur = 0;
for (size_t r = 0; r < numRecvs; ++r) {
recvBuffers[r] = IJVRecvBuffer (cur, recvSizes[r]);
cur += recvSizes[r];
}
}
// perform non-blocking recvs
for (size_t r = 0; r < numRecvs ; ++r) {
// we'll fake the memory management, because all communication
// will be local to this method and the scope of our data
ArrayRCP<Details::CrsIJV<GO, Scalar> > tmparcp =
arcp (recvBuffers[r].getRawPtr (), 0, recvBuffers[r].size (), false);
recvRequests.push_back (ireceive (comm, tmparcp, recvIDs[r]));
}
// perform waits
if (! sendRequests.empty ()) {
waitAll (comm, sendRequests ());
}
if (! recvRequests.empty ()) {
waitAll (comm, recvRequests ());
}
comm.barrier ();
sendRequests.clear ();
recvRequests.clear ();
////////////////////////////////////////////////////////////////////////////////////
// NOW PROCESS THE RECEIVED ROW DATA
////////////////////////////////////////////////////////////////////////////////////
// TODO: instead of adding one entry at a time, add one row at a time.
// this requires resorting; they arrived sorted by sending node, so that entries could be non-contiguous if we received
// multiple entries for a particular row from different processors.
// it also requires restoring the data, which may make it not worth the trouble.
typedef typename Array<Details::CrsIJV<GO, Scalar> >::const_iterator ijv_iter_type;
if (this->isStaticGraph ()) {
for (ijv_iter_type ijv = IJVRecvBuffer.begin ();
ijv != IJVRecvBuffer.end (); ++ijv) {
sumIntoGlobalValues (ijv->i, tuple (ijv->j), tuple (ijv->v));
}
}
else { // Dynamic graph; can use insertGlobalValues ()
for (ijv_iter_type ijv = IJVRecvBuffer.begin ();
ijv != IJVRecvBuffer.end (); ++ijv) {
try {
insertGlobalValues (ijv->i, tuple (ijv->j), tuple (ijv->v));
}
catch (std::runtime_error &e) {
std::ostringstream outmsg;
outmsg << e.what() << std::endl
<< "caught in globalAssemble() in " << __FILE__ << ":" << __LINE__
<< std::endl ;
TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, outmsg.str());
}
}
}
// WHEW! THAT WAS TIRING!
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
resumeFill (const Teuchos::RCP<Teuchos::ParameterList>& params)
{
if (! isStaticGraph ()) { // Don't resume fill of a nonowned graph.
myGraph_->resumeFill (params);
}
clearGlobalConstants ();
fillComplete_ = false;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
computeGlobalConstants ()
{
// This method doesn't do anything. The analogous method in
// CrsGraph does actually compute something.
//
// Oddly enough, clearGlobalConstants() clears frobNorm_ (by
// setting it to -1), but computeGlobalConstants() does _not_
// compute the Frobenius norm; this is done on demand in
// getFrobeniusNorm(), and the result is cached there.
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
clearGlobalConstants () {
// We use -1 to indicate that the Frobenius norm needs to be
// recomputed, since the values might change between now and the
// next fillComplete call.
//
// Oddly enough, clearGlobalConstants() clears frobNorm_, but
// computeGlobalConstants() does _not_ compute the Frobenius norm;
// this is done on demand in getFrobeniusNorm(), and the result is
// cached there.
frobNorm_ = -STM::one ();
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
fillComplete (const RCP<ParameterList>& params)
{
TEUCHOS_TEST_FOR_EXCEPTION(
getCrsGraph ().is_null (), std::logic_error, "Tpetra::CrsMatrix::"
"fillComplete(params): getCrsGraph() returns null. "
"This should not happen at this point. "
"Please report this bug to the Tpetra developers.");
if (isStaticGraph () && getCrsGraph ()->isFillComplete ()) {
fillComplete (getCrsGraph ()->getDomainMap (),
getCrsGraph ()->getRangeMap (), params);
} else {
fillComplete (getRowMap (), getRowMap (), params);
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
fillComplete (const Teuchos::RCP<const map_type>& domainMap,
const Teuchos::RCP<const map_type>& rangeMap,
const Teuchos::RCP<Teuchos::ParameterList>& params)
{
using Teuchos::ArrayRCP;
using Teuchos::RCP;
using Teuchos::rcp;
const char tfecfFuncName[] = "fillComplete";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillActive () || isFillComplete (),
std::runtime_error, ": Matrix fill state must be active (isFillActive() "
"must be true) before you may call fillComplete().");
const int numProcs = getComm ()->getSize ();
//
// Read parameters from the input ParameterList.
//
// If true, the caller promises that no process did nonlocal
// changes since the last call to fillComplete.
bool assertNoNonlocalInserts = false;
// If true, makeColMap sorts remote GIDs (within each remote
// process' group).
bool sortGhosts = true;
if (! params.is_null ()) {
assertNoNonlocalInserts = params->get ("No Nonlocal Changes",
assertNoNonlocalInserts);
if (params->isParameter ("sort column map ghost gids")) {
sortGhosts = params->get ("sort column map ghost gids", sortGhosts);
}
else if (params->isParameter ("Sort column Map ghost GIDs")) {
sortGhosts = params->get ("Sort column Map ghost GIDs", sortGhosts);
}
}
// We also don't need to do global assembly if there is only one
// process in the communicator.
const bool needGlobalAssemble = ! assertNoNonlocalInserts && numProcs > 1;
// This parameter only matters if this matrix owns its graph.
if (! myGraph_.is_null ()) {
myGraph_->sortGhostsAssociatedWithEachProcessor_ = sortGhosts;
}
if (! getCrsGraph()->indicesAreAllocated()) {
if (hasColMap ()) {
// We have a column Map, so use local indices.
allocateValues (LocalIndices, GraphNotYetAllocated);
} else {
// We don't have a column Map, so use global indices.
allocateValues (GlobalIndices, GraphNotYetAllocated);
}
}
// Global assemble, if we need to. This call only costs a single
// all-reduce if we didn't need global assembly after all.
if (needGlobalAssemble) {
globalAssemble ();
}
else {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
numProcs == 1 && nonlocals_.size() > 0,
std::runtime_error, ": cannot have nonlocal entries on a serial run. "
"An invalid entry (i.e., with row index not in the row Map) must have "
"been submitted to the CrsMatrix.");
}
if (isStaticGraph ()) {
// FIXME (mfh 18 Jun 2014) This check for correctness of the
// input Maps incurs a penalty of two all-reduces for the
// otherwise optimal const graph case.
//
// We could turn these (max) 2 all-reduces into (max) 1, by
// fusing them. We could do this by adding a "locallySameAs"
// method to Map, which would return one of four states:
//
// a. Certainly globally the same
// b. Certainly globally not the same
// c. Locally the same
// d. Locally not the same
//
// The first two states don't require further communication.
// The latter two states require an all-reduce to communicate
// globally, but we only need one all-reduce, since we only need
// to check whether at least one of the Maps is wrong.
const bool domainMapsMatch = staticGraph_->getDomainMap ()->isSameAs (*domainMap);
const bool rangeMapsMatch = staticGraph_->getRangeMap ()->isSameAs (*rangeMap);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! domainMapsMatch, std::runtime_error,
": The CrsMatrix's domain Map does not match the graph's domain Map. "
"The graph cannot be changed because it was given to the CrsMatrix "
"constructor as const. You can fix this by passing in the graph's "
"domain Map and range Map to the matrix's fillComplete call.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! rangeMapsMatch, std::runtime_error,
": The CrsMatrix's range Map does not match the graph's range Map. "
"The graph cannot be changed because it was given to the CrsMatrix "
"constructor as const. You can fix this by passing in the graph's "
"domain Map and range Map to the matrix's fillComplete call.");
}
else {
// Set the graph's domain and range Maps. This will clear the
// Import if the domain Map has changed (is a different
// pointer), and the Export if the range Map has changed (is a
// different pointer).
myGraph_->setDomainRangeMaps (domainMap, rangeMap);
// Make the graph's column Map, if necessary.
if (! myGraph_->hasColMap ()) {
myGraph_->makeColMap ();
}
// Make indices local, if necessary. The method won't do
// anything if the graph is already locally indexed.
myGraph_->makeIndicesLocal ();
if (! myGraph_->isSorted ()) {
sortEntries ();
}
if (! myGraph_->isMerged ()) {
mergeRedundantEntries ();
}
// Make the Import and Export, if they haven't been made already.
myGraph_->makeImportExport ();
myGraph_->computeGlobalConstants ();
myGraph_->fillComplete_ = true;
myGraph_->checkInternalState ();
}
computeGlobalConstants ();
// fill local objects; will fill and finalize local graph if appropriate
if (myGraph_.is_null ()) {
// The matrix does _not_ own the graph, and the graph's
// structure is already fixed, so just fill the local matrix.
fillLocalMatrix (params);
} else {
// The matrix _does_ own the graph, so fill the local graph at
// the same time as the local matrix.
fillLocalGraphAndMatrix (params);
}
// Once we've initialized the sparse kernels, we're done with the
// local objects. We may now release them and their memory, since
// they will persist in the local sparse ops if necessary. We
// keep the local graph if the parameters tell us to do so.
// FIXME (mfh 28 Aug 2014) "Preserve Local Graph" bool parameter no longer used.
fillComplete_ = true; // Now we're fill complete!
checkInternalState ();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
expertStaticFillComplete (const Teuchos::RCP<const map_type> & domainMap,
const Teuchos::RCP<const map_type> & rangeMap,
const Teuchos::RCP<const import_type>& importer,
const Teuchos::RCP<const export_type>& exporter,
const Teuchos::RCP<Teuchos::ParameterList> ¶ms)
{
#ifdef HAVE_TPETRA_MMM_TIMINGS
std::string label;
if(!params.is_null())
label = params->get("Timer Label",label);
std::string prefix = std::string("Tpetra ")+ label + std::string(": ");
using Teuchos::TimeMonitor;
Teuchos::RCP<Teuchos::TimeMonitor> MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-M-Graph"))));
#endif
const char tfecfFuncName[] = "expertStaticFillComplete: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( ! isFillActive() || isFillComplete(),
std::runtime_error, "Matrix fill state must be active (isFillActive() "
"must be true) before calling fillComplete().");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
myGraph_.is_null (), std::logic_error, "myGraph_ is null. This is not allowed.");
// We will presume globalAssemble is not needed, so we do the ESFC on the graph
myGraph_->expertStaticFillComplete (domainMap, rangeMap, importer, exporter,params);
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-M-cGC"))));
#endif
computeGlobalConstants ();
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-M-fLGAM"))));
#endif
// Fill the local graph and matrix
fillLocalGraphAndMatrix (params);
// FIXME (mfh 28 Aug 2014) "Preserve Local Graph" bool parameter no longer used.
// Now we're fill complete!
fillComplete_ = true;
// Sanity checks at the end.
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(isFillActive(), std::logic_error,
": We're at the end of fillComplete(), but isFillActive() is true. "
"Please report this bug to the Tpetra developers.");
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! isFillComplete(), std::logic_error,
": We're at the end of fillComplete(), but isFillActive() is true. "
"Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-M-cIS"))));
#endif
checkInternalState();
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
sortEntries ()
{
TEUCHOS_TEST_FOR_EXCEPTION(
isStaticGraph (), std::runtime_error, "Tpetra::CrsMatrix::sortEntries: "
"Cannot sort with static graph.");
if (! myGraph_->isSorted ()) {
const size_t lclNumRows = this->getNodeNumRows ();
for (size_t row = 0; row < lclNumRows; ++row) {
RowInfo rowInfo = myGraph_->getRowInfo (row);
Teuchos::ArrayView<impl_scalar_type> rv = this->getViewNonConst (rowInfo);
myGraph_->template sortRowIndicesAndValues<impl_scalar_type> (rowInfo, rv);
}
// we just sorted every row
myGraph_->indicesAreSorted_ = true;
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
mergeRedundantEntries ()
{
TEUCHOS_TEST_FOR_EXCEPTION(
isStaticGraph (), std::runtime_error, "Tpetra::CrsMatrix::"
"mergeRedundantEntries: Cannot merge with static graph.");
if (! myGraph_->isMerged ()) {
const size_t lclNumRows = this->getNodeNumRows ();
for (size_t row = 0; row < lclNumRows; ++row) {
RowInfo rowInfo = myGraph_->getRowInfo (row);
Teuchos::ArrayView<impl_scalar_type> rv = this->getViewNonConst (rowInfo);
myGraph_->template mergeRowIndicesAndValues<impl_scalar_type> (rowInfo, rv);
}
myGraph_->noRedundancies_ = true; // we just merged every row
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
applyNonTranspose (const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> & X_in,
MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> & Y_in,
Scalar alpha,
Scalar beta) const
{
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcp_const_cast;
using Teuchos::rcpFromRef;
const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero ();
const Scalar ONE = Teuchos::ScalarTraits<Scalar>::one ();
// mfh 05 Jun 2014: Special case for alpha == 0. I added this to
// fix an Ifpack2 test (RILUKSingleProcessUnitTests), which was
// failing only for the Kokkos refactor version of Tpetra. It's a
// good idea regardless to have the bypass.
if (alpha == ZERO) {
if (beta == ZERO) {
Y_in.putScalar (ZERO);
} else if (beta != ONE) {
Y_in.scale (beta);
}
return;
}
// It's possible that X is a view of Y or vice versa. We don't
// allow this (apply() requires that X and Y not alias one
// another), but it's helpful to detect and work around this case.
// We don't try to to detect the more subtle cases (e.g., one is a
// subview of the other, but their initial pointers differ). We
// only need to do this if this matrix's Import is trivial;
// otherwise, we don't actually apply the operator from X into Y.
RCP<const import_type> importer = this->getGraph ()->getImporter ();
RCP<const export_type> exporter = this->getGraph ()->getExporter ();
// If beta == 0, then the output MV will be overwritten; none of
// its entries should be read. (Sparse BLAS semantics say that we
// must ignore any Inf or NaN entries in Y_in, if beta is zero.)
// This matters if we need to do an Export operation; see below.
const bool Y_is_overwritten = (beta == ZERO);
// We treat the case of a replicated MV output specially.
const bool Y_is_replicated = ! Y_in.isDistributed ();
// This is part of the special case for replicated MV output.
// We'll let each process do its thing, but do an all-reduce at
// the end to sum up the results. Setting beta=0 on all processes
// but Proc 0 makes the math work out for the all-reduce. (This
// assumes that the replicated data is correctly replicated, so
// that the data are the same on all processes.)
if (Y_is_replicated && this->getComm ()->getRank () > 0) {
beta = ZERO;
}
// Temporary MV for Import operation. After the block of code
// below, this will be an (Imported if necessary) column Map MV
// ready to give to localMultiply().
RCP<const MV> X_colMap;
if (importer.is_null ()) {
if (! X_in.isConstantStride ()) {
// Not all sparse mat-vec kernels can handle an input MV with
// nonconstant stride correctly, so we have to copy it in that
// case into a constant stride MV. To make a constant stride
// copy of X_in, we force creation of the column (== domain)
// Map MV (if it hasn't already been created, else fetch the
// cached copy). This avoids creating a new MV each time.
RCP<MV> X_colMapNonConst = getColumnMapMultiVector (X_in, true);
Tpetra::deep_copy (*X_colMapNonConst, X_in);
X_colMap = rcp_const_cast<const MV> (X_colMapNonConst);
}
else {
// The domain and column Maps are the same, so do the local
// multiply using the domain Map input MV X_in.
X_colMap = rcpFromRef (X_in);
}
}
else {
// We're doing an Import anyway, which will copy the relevant
// elements of the domain Map MV X_in into a separate column Map
// MV. Thus, we don't have to worry whether X_in is constant
// stride.
RCP<MV> X_colMapNonConst = getColumnMapMultiVector (X_in);
// Import from the domain Map MV to the column Map MV.
X_colMapNonConst->doImport (X_in, *importer, INSERT);
X_colMap = rcp_const_cast<const MV> (X_colMapNonConst);
}
// Temporary MV for Export operation, or for copying a nonconstant
// stride output MV into a constant stride MV.
RCP<MV> Y_rowMap = getRowMapMultiVector (Y_in);
// If we have a nontrivial Export object, we must perform an
// Export. In that case, the local multiply result will go into
// the row Map multivector. We don't have to make a
// constant-stride version of Y_in in this case, because we had to
// make a constant stride Y_rowMap MV and do an Export anyway.
if (! exporter.is_null ()) {
this->template localMultiply<Scalar, Scalar> (*X_colMap, *Y_rowMap,
Teuchos::NO_TRANS,
alpha, ZERO);
// If we're overwriting the output MV Y_in completely (beta ==
// 0), then make sure that it is filled with zeros before we do
// the Export. Otherwise, the ADD combine mode will use data in
// Y_in, which is supposed to be zero.
if (Y_is_overwritten) {
Y_in.putScalar (ZERO);
}
else {
// Scale the output MV by beta, so that the Export sums in the
// mat-vec contribution: Y_in = beta*Y_in + alpha*A*X_in.
Y_in.scale (beta);
}
// Do the Export operation.
Y_in.doExport (*Y_rowMap, *exporter, ADD);
}
else { // Don't do an Export: row Map and range Map are the same.
//
// If Y_in does not have constant stride, or if the column Map
// MV aliases Y_in, then we can't let the kernel write directly
// to Y_in. Instead, we have to use the cached row (== range)
// Map MV as temporary storage.
//
// FIXME (mfh 05 Jun 2014) This test for aliasing only tests if
// the user passed in the same MultiVector for both X and Y. It
// won't detect whether one MultiVector views the other. We
// should also check the MultiVectors' raw data pointers.
if (! Y_in.isConstantStride () || X_colMap.getRawPtr () == &Y_in) {
// Force creating the MV if it hasn't been created already.
// This will reuse a previously created cached MV.
Y_rowMap = getRowMapMultiVector (Y_in, true);
// If beta == 0, we don't need to copy Y_in into Y_rowMap,
// since we're overwriting it anyway.
if (beta != ZERO) {
Tpetra::deep_copy (*Y_rowMap, Y_in);
}
this->template localMultiply<Scalar, Scalar> (*X_colMap,
*Y_rowMap,
Teuchos::NO_TRANS,
alpha, beta);
Tpetra::deep_copy (Y_in, *Y_rowMap);
}
else {
this->template localMultiply<Scalar, Scalar> (*X_colMap, Y_in,
Teuchos::NO_TRANS,
alpha, beta);
}
}
// If the range Map is a locally replicated Map, sum up
// contributions from each process. We set beta = 0 on all
// processes but Proc 0 initially, so this will handle the scaling
// factor beta correctly.
if (Y_is_replicated) {
Y_in.reduce ();
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
applyTranspose (const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& X_in,
MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& Y_in,
const Teuchos::ETransp mode,
Scalar alpha,
Scalar beta) const
{
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcp_const_cast;
using Teuchos::rcpFromRef;
const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero ();
// Take shortcuts for alpha == 0.
if (alpha == ZERO) {
// Follow the Sparse BLAS convention by ignoring both the matrix
// and X_in, in this case.
if (beta == ZERO) {
// Follow the Sparse BLAS convention by overwriting any Inf or
// NaN values in Y_in, in this case.
Y_in.putScalar (ZERO);
}
else {
Y_in.scale (beta);
}
return;
}
const size_t numVectors = X_in.getNumVectors ();
// We don't allow X_in and Y_in to alias one another. It's hard
// to check this, because advanced users could create views from
// raw pointers. However, if X_in and Y_in reference the same
// object, we will do the user a favor by copying X into new
// storage (with a warning). We only need to do this if we have
// trivial importers; otherwise, we don't actually apply the
// operator from X into Y.
RCP<const import_type> importer = this->getGraph ()->getImporter ();
RCP<const export_type> exporter = this->getGraph ()->getExporter ();
// access X indirectly, in case we need to create temporary storage
RCP<const MV> X;
// some parameters for below
const bool Y_is_replicated = ! Y_in.isDistributed ();
const bool Y_is_overwritten = (beta == ZERO);
if (Y_is_replicated && this->getComm ()->getRank () > 0) {
beta = ZERO;
}
// The kernels do not allow input or output with nonconstant stride.
if (! X_in.isConstantStride () && importer.is_null ()) {
X = rcp (new MV (X_in, Teuchos::Copy)); // Constant-stride copy of X_in
} else {
X = rcpFromRef (X_in); // Reference to X_in
}
// Set up temporary multivectors for Import and/or Export.
if (importer != null) {
if (importMV_ != null && importMV_->getNumVectors() != numVectors) {
importMV_ = null;
}
if (importMV_ == null) {
importMV_ = rcp (new MV (this->getColMap (), numVectors));
}
}
if (exporter != null) {
if (exportMV_ != null && exportMV_->getNumVectors() != numVectors) {
exportMV_ = null;
}
if (exportMV_ == null) {
exportMV_ = rcp (new MV (this->getRowMap (), numVectors));
}
}
// If we have a non-trivial exporter, we must import elements that
// are permuted or are on other processors.
if (! exporter.is_null ()) {
exportMV_->doImport (X_in, *exporter, INSERT);
X = exportMV_; // multiply out of exportMV_
}
// If we have a non-trivial importer, we must export elements that
// are permuted or belong to other processors. We will compute
// solution into the to-be-exported MV; get a view.
if (importer != null) {
// FIXME (mfh 18 Apr 2015) Temporary fix suggested by Clark
// Dohrmann on Fri 17 Apr 2015. At some point, we need to go
// back and figure out why this helps. importMV_ SHOULD be
// completely overwritten in the localMultiply() call below,
// because beta == ZERO there.
importMV_->putScalar (ZERO);
// Do the local computation.
this->template localMultiply<Scalar, Scalar> (*X, *importMV_, mode,
alpha, ZERO);
if (Y_is_overwritten) {
Y_in.putScalar (ZERO);
} else {
Y_in.scale (beta);
}
Y_in.doExport (*importMV_, *importer, ADD);
}
// otherwise, multiply into Y
else {
// can't multiply in-situ; can't multiply into non-strided multivector
//
// FIXME (mfh 05 Jun 2014) This test for aliasing only tests if
// the user passed in the same MultiVector for both X and Y. It
// won't detect whether one MultiVector views the other. We
// should also check the MultiVectors' raw data pointers.
if (! Y_in.isConstantStride () || X.getRawPtr () == &Y_in) {
// Make a deep copy of Y_in, into which to write the multiply result.
MV Y (Y_in, Teuchos::Copy);
this->template localMultiply<Scalar, Scalar> (*X, Y, mode, alpha, beta);
Tpetra::deep_copy (Y_in, Y);
} else {
this->template localMultiply<Scalar, Scalar> (*X, Y_in, mode, alpha, beta);
}
}
// If the range Map is a locally replicated map, sum the
// contributions from each process. (That's why we set beta=0
// above for all processes but Proc 0.)
if (Y_is_replicated) {
Y_in.reduce ();
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
apply (const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> &X,
MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> &Y,
Teuchos::ETransp mode,
Scalar alpha,
Scalar beta) const
{
TEUCHOS_TEST_FOR_EXCEPTION(
! isFillComplete (), std::runtime_error,
"Tpetra::CrsMatrix::apply(): Cannot call apply() until fillComplete() "
"has been called.");
if (mode == Teuchos::NO_TRANS) {
applyNonTranspose (X, Y, alpha, beta);
} else {
//Thyra was implicitly assuming that Y gets set to zero / or is overwritten
//when bets==0. This was not the case with transpose in a multithreaded
//environment where a multiplication with subsequent atomic_adds is used
//since 0 is effectively not special cased. Doing the explicit set to zero here
//This catches cases where Y is nan or inf.
const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero ();
if(beta == ZERO)
Y.putScalar (ZERO);
applyTranspose (X, Y, mode, alpha, beta);
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
gaussSeidel (const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& B,
MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& X,
const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& D,
const Scalar& dampingFactor,
const ESweepDirection direction,
const int numSweeps) const
{
reorderedGaussSeidel (B, X, D, Teuchos::null, dampingFactor, direction, numSweeps);
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
reorderedGaussSeidel (const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& B,
MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& X,
const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& D,
const Teuchos::ArrayView<LocalOrdinal>& rowIndices,
const Scalar& dampingFactor,
const ESweepDirection direction,
const int numSweeps) const
{
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcp_const_cast;
using Teuchos::rcpFromRef;
typedef Scalar ST;
TEUCHOS_TEST_FOR_EXCEPTION(
isFillComplete() == false, std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel: cannot call this method until "
"fillComplete() has been called.");
TEUCHOS_TEST_FOR_EXCEPTION(
numSweeps < 0,
std::invalid_argument,
"Tpetra::CrsMatrix::gaussSeidel: The number of sweeps must be , "
"nonnegative but you provided numSweeps = " << numSweeps << " < 0.");
// Translate from global to local sweep direction.
// While doing this, validate the input.
KokkosClassic::ESweepDirection localDirection;
if (direction == Forward) {
localDirection = KokkosClassic::Forward;
}
else if (direction == Backward) {
localDirection = KokkosClassic::Backward;
}
else if (direction == Symmetric) {
// We'll control local sweep direction manually.
localDirection = KokkosClassic::Forward;
}
else {
TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument,
"Tpetra::CrsMatrix::gaussSeidel: The 'direction' enum does not have "
"any of its valid values: Forward, Backward, or Symmetric.");
}
if (numSweeps == 0) {
return; // Nothing to do.
}
// We don't need the Export object because this method assumes
// that the row, domain, and range Maps are the same. We do need
// the Import object, if there is one, though.
RCP<const import_type> importer = this->getGraph()->getImporter();
RCP<const export_type> exporter = this->getGraph()->getExporter();
TEUCHOS_TEST_FOR_EXCEPTION(
! exporter.is_null (), std::runtime_error,
"Tpetra's gaussSeidel implementation requires that the row, domain, "
"and range Maps be the same. This cannot be the case, because the "
"matrix has a nontrivial Export object.");
RCP<const map_type> domainMap = this->getDomainMap ();
RCP<const map_type> rangeMap = this->getRangeMap ();
RCP<const map_type> rowMap = this->getGraph ()->getRowMap ();
RCP<const map_type> colMap = this->getGraph ()->getColMap ();
#ifdef HAVE_TEUCHOS_DEBUG
{
// The relation 'isSameAs' is transitive. It's also a
// collective, so we don't have to do a "shared" test for
// exception (i.e., a global reduction on the test value).
TEUCHOS_TEST_FOR_EXCEPTION(
! X.getMap ()->isSameAs (*domainMap),
std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel requires that the input "
"multivector X be in the domain Map of the matrix.");
TEUCHOS_TEST_FOR_EXCEPTION(
! B.getMap ()->isSameAs (*rangeMap),
std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel requires that the input "
"B be in the range Map of the matrix.");
TEUCHOS_TEST_FOR_EXCEPTION(
! D.getMap ()->isSameAs (*rowMap),
std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel requires that the input "
"D be in the row Map of the matrix.");
TEUCHOS_TEST_FOR_EXCEPTION(
! rowMap->isSameAs (*rangeMap),
std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel requires that the row Map and the "
"range Map be the same (in the sense of Tpetra::Map::isSameAs).");
TEUCHOS_TEST_FOR_EXCEPTION(
! domainMap->isSameAs (*rangeMap),
std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel requires that the domain Map and "
"the range Map of the matrix be the same.");
}
#else
// Forestall any compiler warnings for unused variables.
(void) rangeMap;
(void) rowMap;
#endif // HAVE_TEUCHOS_DEBUG
// If B is not constant stride, copy it into a constant stride
// multivector. We'l handle the right-hand side B first and deal
// with X right before the sweeps, to improve locality of the
// first sweep. (If the problem is small enough, then that will
// hopefully keep more of the entries of X in cache. This
// optimizes for the typical case of a small number of sweeps.)
RCP<const MV> B_in;
if (B.isConstantStride()) {
B_in = rcpFromRef (B);
}
else {
// The range Map and row Map are the same in this case, so we
// can use the (possibly cached) row Map multivector to store a
// constant stride copy of B. We don't have to copy back, since
// Gauss-Seidel won't modify B.
RCP<MV> B_in_nonconst = getRowMapMultiVector (B, true);
deep_copy (*B_in_nonconst, B); // Copy from B into B_in(_nonconst).
B_in = rcp_const_cast<const MV> (B_in_nonconst);
TPETRA_EFFICIENCY_WARNING(
! B.isConstantStride (),
std::runtime_error,
"gaussSeidel: The current implementation of the Gauss-Seidel kernel "
"requires that X and B both have constant stride. Since B does not "
"have constant stride, we had to make a copy. This is a limitation of "
"the current implementation and not your fault, but we still report it "
"as an efficiency warning for your information.");
}
// If X is not constant stride, copy it into a constant stride
// multivector. Also, make the column Map multivector X_colMap,
// and its domain Map view X_domainMap. (X actually must be a
// domain Map view of a column Map multivector; exploit this, if X
// has constant stride.)
RCP<MV> X_domainMap;
RCP<MV> X_colMap;
bool copiedInput = false;
if (importer.is_null ()) { // Domain and column Maps are the same.
if (X.isConstantStride ()) {
X_domainMap = rcpFromRef (X);
X_colMap = X_domainMap;
copiedInput = false;
}
else {
// Get a temporary column Map multivector, make a domain Map
// view of it, and copy X into the domain Map view. We have
// to copy here because we won't be doing Import operations.
X_colMap = getColumnMapMultiVector (X, true);
X_domainMap = X_colMap; // Domain and column Maps are the same.
deep_copy (*X_domainMap, X); // Copy X into the domain Map view.
copiedInput = true;
TPETRA_EFFICIENCY_WARNING(
! X.isConstantStride (), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel: The current implementation of the "
"Gauss-Seidel kernel requires that X and B both have constant "
"stride. Since X does not have constant stride, we had to make a "
"copy. This is a limitation of the current implementation and not "
"your fault, but we still report it as an efficiency warning for "
"your information.");
}
}
else { // We will be doing Import operations in the sweeps.
if (X.isConstantStride ()) {
X_domainMap = rcpFromRef (X);
// This kernel assumes that X is a domain Map view of a column
// Map multivector. We will only check if this is valid if
// the CMake configure Teuchos_ENABLE_DEBUG is ON.
X_colMap = X_domainMap->offsetViewNonConst (colMap, 0);
// FIXME (mfh 19 Mar 2013) Do we need to fill the remote
// entries of X_colMap with zeros? Do we need to fill all of
// X_domainMap initially with zeros? Ifpack
// (Ifpack_PointRelaxation.cpp, line 906) creates an entirely
// new MultiVector each time.
// Do the first Import for the first sweep. This simplifies
// the logic in the sweeps.
X_colMap->doImport (X, *importer, INSERT);
copiedInput = false;
}
else {
// Get a temporary column Map multivector X_colMap, and make a
// domain Map view X_domainMap of it. Instead of copying, we
// do an Import from X into X_domainMap. This saves us a
// copy, since the Import has to copy the data anyway.
X_colMap = getColumnMapMultiVector (X, true);
X_domainMap = X_colMap->offsetViewNonConst (domainMap, 0);
X_colMap->doImport (X, *importer, INSERT);
copiedInput = true;
TPETRA_EFFICIENCY_WARNING(
! X.isConstantStride (), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidel: The current implementation of the "
"Gauss-Seidel kernel requires that X and B both have constant stride. "
"Since X does not have constant stride, we had to make a copy. "
"This is a limitation of the current implementation and not your fault, "
"but we still report it as an efficiency warning for your information.");
}
}
for (int sweep = 0; sweep < numSweeps; ++sweep) {
if (! importer.is_null () && sweep > 0) {
// We already did the first Import for the zeroth sweep.
X_colMap->doImport (*X_domainMap, *importer, INSERT);
}
// Do local Gauss-Seidel.
if (direction != Symmetric) {
if (rowIndices.is_null ()) {
this->template localGaussSeidel<ST, ST> (*B_in, *X_colMap, D,
dampingFactor,
localDirection);
}
else {
this->template reorderedLocalGaussSeidel<ST, ST> (*B_in, *X_colMap,
D, rowIndices,
dampingFactor,
localDirection);
}
}
else { // direction == Symmetric
const bool doImportBetweenDirections = false;
if (rowIndices.is_null ()) {
this->template localGaussSeidel<ST, ST> (*B_in, *X_colMap, D,
dampingFactor,
KokkosClassic::Forward);
// mfh 18 Mar 2013: Aztec's implementation of "symmetric
// Gauss-Seidel" does _not_ do an Import between the forward
// and backward sweeps. This makes sense, because Aztec
// considers "symmetric Gauss-Seidel" a subdomain solver.
if (doImportBetweenDirections) {
// Communicate again before the Backward sweep.
if (! importer.is_null ()) {
X_colMap->doImport (*X_domainMap, *importer, INSERT);
}
}
this->template localGaussSeidel<ST, ST> (*B_in, *X_colMap, D,
dampingFactor,
KokkosClassic::Backward);
}
else {
this->template reorderedLocalGaussSeidel<ST, ST> (*B_in, *X_colMap,
D, rowIndices,
dampingFactor,
KokkosClassic::Forward);
if (doImportBetweenDirections) {
// Communicate again before the Backward sweep.
if (! importer.is_null ()) {
X_colMap->doImport (*X_domainMap, *importer, INSERT);
}
}
this->template reorderedLocalGaussSeidel<ST, ST> (*B_in, *X_colMap,
D, rowIndices,
dampingFactor,
KokkosClassic::Backward);
}
}
}
if (copiedInput) {
deep_copy (X, *X_domainMap); // Copy back from X_domainMap to X.
}
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
gaussSeidelCopy (MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& X,
const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& B,
const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& D,
const Scalar& dampingFactor,
const ESweepDirection direction,
const int numSweeps,
const bool zeroInitialGuess) const
{
reorderedGaussSeidelCopy (X, B, D, Teuchos::null, dampingFactor, direction,
numSweeps, zeroInitialGuess);
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
reorderedGaussSeidelCopy (MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& X,
const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& B,
const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& D,
const Teuchos::ArrayView<LocalOrdinal>& rowIndices,
const Scalar& dampingFactor,
const ESweepDirection direction,
const int numSweeps,
const bool zeroInitialGuess) const
{
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcpFromRef;
using Teuchos::rcp_const_cast;
typedef Scalar ST;
const char prefix[] = "Tpetra::CrsMatrix::(reordered)gaussSeidelCopy: ";
const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero ();
TEUCHOS_TEST_FOR_EXCEPTION(
! isFillComplete (), std::runtime_error,
prefix << "The matrix is not fill complete.");
TEUCHOS_TEST_FOR_EXCEPTION(
numSweeps < 0, std::invalid_argument,
prefix << "The number of sweeps must be nonnegative, "
"but you provided numSweeps = " << numSweeps << " < 0.");
// Translate from global to local sweep direction.
// While doing this, validate the input.
KokkosClassic::ESweepDirection localDirection;
if (direction == Forward) {
localDirection = KokkosClassic::Forward;
}
else if (direction == Backward) {
localDirection = KokkosClassic::Backward;
}
else if (direction == Symmetric) {
// We'll control local sweep direction manually.
localDirection = KokkosClassic::Forward;
}
else {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
prefix << "The 'direction' enum does not have any of its valid "
"values: Forward, Backward, or Symmetric.");
}
if (numSweeps == 0) {
return;
}
RCP<const import_type> importer = this->getGraph ()->getImporter ();
RCP<const export_type> exporter = this->getGraph ()->getExporter ();
TEUCHOS_TEST_FOR_EXCEPTION(
! exporter.is_null (), std::runtime_error,
"This method's implementation currently requires that the matrix's row, "
"domain, and range Maps be the same. This cannot be the case, because "
"the matrix has a nontrivial Export object.");
RCP<const map_type> domainMap = this->getDomainMap ();
RCP<const map_type> rangeMap = this->getRangeMap ();
RCP<const map_type> rowMap = this->getGraph ()->getRowMap ();
RCP<const map_type> colMap = this->getGraph ()->getColMap ();
#ifdef HAVE_TEUCHOS_DEBUG
{
// The relation 'isSameAs' is transitive. It's also a
// collective, so we don't have to do a "shared" test for
// exception (i.e., a global reduction on the test value).
TEUCHOS_TEST_FOR_EXCEPTION(
! X.getMap ()->isSameAs (*domainMap), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidelCopy requires that the input "
"multivector X be in the domain Map of the matrix.");
TEUCHOS_TEST_FOR_EXCEPTION(
! B.getMap ()->isSameAs (*rangeMap), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidelCopy requires that the input "
"B be in the range Map of the matrix.");
TEUCHOS_TEST_FOR_EXCEPTION(
! D.getMap ()->isSameAs (*rowMap), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidelCopy requires that the input "
"D be in the row Map of the matrix.");
TEUCHOS_TEST_FOR_EXCEPTION(
! rowMap->isSameAs (*rangeMap), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidelCopy requires that the row Map and the "
"range Map be the same (in the sense of Tpetra::Map::isSameAs).");
TEUCHOS_TEST_FOR_EXCEPTION(
! domainMap->isSameAs (*rangeMap), std::runtime_error,
"Tpetra::CrsMatrix::gaussSeidelCopy requires that the domain Map and "
"the range Map of the matrix be the same.");
}
#else
// Forestall any compiler warnings for unused variables.
(void) rangeMap;
(void) rowMap;
#endif // HAVE_TEUCHOS_DEBUG
// Fetch a (possibly cached) temporary column Map multivector
// X_colMap, and a domain Map view X_domainMap of it. Both have
// constant stride by construction. We know that the domain Map
// must include the column Map, because our Gauss-Seidel kernel
// requires that the row Map, domain Map, and range Map are all
// the same, and that each process owns all of its own diagonal
// entries of the matrix.
RCP<MV> X_colMap;
RCP<MV> X_domainMap;
bool copyBackOutput = false;
if (importer.is_null ()) {
if (X.isConstantStride ()) {
X_colMap = rcpFromRef (X);
X_domainMap = rcpFromRef (X);
// Column Map and domain Map are the same, so there are no
// remote entries. Thus, if we are not setting the initial
// guess to zero, we don't have to worry about setting remote
// entries to zero, even though we are not doing an Import in
// this case.
if (zeroInitialGuess) {
X_colMap->putScalar (ZERO);
}
// No need to copy back to X at end.
}
else { // We must copy X into a constant stride multivector.
// Just use the cached column Map multivector for that.
// force=true means fill with zeros, so no need to fill
// remote entries (not in domain Map) with zeros.
X_colMap = getColumnMapMultiVector (X, true);
// X_domainMap is always a domain Map view of the column Map
// multivector. In this case, the domain and column Maps are
// the same, so X_domainMap _is_ X_colMap.
X_domainMap = X_colMap;
if (! zeroInitialGuess) { // Don't copy if zero initial guess
try {
deep_copy (*X_domainMap , X); // Copy X into constant stride MV
} catch (std::exception& e) {
std::ostringstream os;
os << "Tpetra::CrsMatrix::reorderedGaussSeidelCopy: "
"deep_copy(*X_domainMap, X) threw an exception: "
<< e.what () << ".";
TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, e.what ());
}
}
copyBackOutput = true; // Don't forget to copy back at end.
TPETRA_EFFICIENCY_WARNING(
! X.isConstantStride (),
std::runtime_error,
"gaussSeidelCopy: The current implementation of the Gauss-Seidel "
"kernel requires that X and B both have constant stride. Since X "
"does not have constant stride, we had to make a copy. This is a "
"limitation of the current implementation and not your fault, but we "
"still report it as an efficiency warning for your information.");
}
}
else { // Column Map and domain Map are _not_ the same.
X_colMap = getColumnMapMultiVector (X);
X_domainMap = X_colMap->offsetViewNonConst (domainMap, 0);
#ifdef HAVE_TPETRA_DEBUG
typename MV::dual_view_type X_colMap_view = X_colMap->getDualView ();
typename MV::dual_view_type X_domainMap_view = X_domainMap->getDualView ();
if (X_colMap->getLocalLength () != 0 && X_domainMap->getLocalLength ()) {
TEUCHOS_TEST_FOR_EXCEPTION(
X_colMap_view.h_view.ptr_on_device () != X_domainMap_view.h_view.ptr_on_device (),
std::logic_error, "Tpetra::CrsMatrix::gaussSeidelCopy: "
"Pointer to start of column Map view of X is not equal to pointer to "
"start of (domain Map view of) X. This may mean that "
"Tpetra::MultiVector::offsetViewNonConst is broken. "
"Please report this bug to the Tpetra developers.");
}
TEUCHOS_TEST_FOR_EXCEPTION(
X_colMap_view.dimension_0 () < X_domainMap_view.dimension_0 () ||
X_colMap->getLocalLength () < X_domainMap->getLocalLength (),
std::logic_error, "Tpetra::CrsMatrix::gaussSeidelCopy: "
"X_colMap has fewer local rows than X_domainMap. "
"X_colMap_view.dimension_0() = " << X_colMap_view.dimension_0 ()
<< ", X_domainMap_view.dimension_0() = "
<< X_domainMap_view.dimension_0 ()
<< ", X_colMap->getLocalLength() = " << X_colMap->getLocalLength ()
<< ", and X_domainMap->getLocalLength() = "
<< X_domainMap->getLocalLength ()
<< ". This means that Tpetra::MultiVector::offsetViewNonConst "
"is broken. Please report this bug to the Tpetra developers.");
TEUCHOS_TEST_FOR_EXCEPTION(
X_colMap->getNumVectors () != X_domainMap->getNumVectors (),
std::logic_error, "Tpetra::CrsMatrix::gaussSeidelCopy: "
"X_colMap has a different number of columns than X_domainMap. "
"X_colMap->getNumVectors() = " << X_colMap->getNumVectors ()
<< " != X_domainMap->getNumVectors() = "
<< X_domainMap->getNumVectors ()
<< ". This means that Tpetra::MultiVector::offsetViewNonConst "
"is broken. Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
if (zeroInitialGuess) {
// No need for an Import, since we're filling with zeros.
X_colMap->putScalar (ZERO);
} else {
// We could just copy X into X_domainMap. However, that
// wastes a copy, because the Import also does a copy (plus
// communication). Since the typical use case for
// Gauss-Seidel is a small number of sweeps (2 is typical), we
// don't want to waste that copy. Thus, we do the Import
// here, and skip the first Import in the first sweep.
// Importing directly from X effects the copy into X_domainMap
// (which is a view of X_colMap).
X_colMap->doImport (X, *importer, INSERT);
}
copyBackOutput = true; // Don't forget to copy back at end.
} // if column and domain Maps are (not) the same
// The Gauss-Seidel / SOR kernel expects multivectors of constant
// stride. X_colMap is by construction, but B might not be. If
// it's not, we have to make a copy.
RCP<const MV> B_in;
if (B.isConstantStride ()) {
B_in = rcpFromRef (B);
}
else {
// Range Map and row Map are the same in this case, so we can
// use the cached row Map multivector to store a constant stride
// copy of B.
RCP<MV> B_in_nonconst = getRowMapMultiVector (B, true);
try {
deep_copy (*B_in_nonconst, B);
} catch (std::exception& e) {
std::ostringstream os;
os << "Tpetra::CrsMatrix::reorderedGaussSeidelCopy: "
"deep_copy(*B_in_nonconst, B) threw an exception: "
<< e.what () << ".";
TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, e.what ());
}
B_in = rcp_const_cast<const MV> (B_in_nonconst);
TPETRA_EFFICIENCY_WARNING(
! B.isConstantStride (),
std::runtime_error,
"gaussSeidelCopy: The current implementation requires that B have "
"constant stride. Since B does not have constant stride, we had to "
"copy it into a separate constant-stride multivector. This is a "
"limitation of the current implementation and not your fault, but we "
"still report it as an efficiency warning for your information.");
}
for (int sweep = 0; sweep < numSweeps; ++sweep) {
if (! importer.is_null () && sweep > 0) {
// We already did the first Import for the zeroth sweep above,
// if it was necessary.
X_colMap->doImport (*X_domainMap, *importer, INSERT);
}
// Do local Gauss-Seidel.
if (direction != Symmetric) {
if (rowIndices.is_null ()) {
this->template localGaussSeidel<ST, ST> (*B_in, *X_colMap, D,
dampingFactor,
localDirection);
}
else {
this->template reorderedLocalGaussSeidel<ST, ST> (*B_in, *X_colMap,
D, rowIndices,
dampingFactor,
localDirection);
}
}
else { // direction == Symmetric
if (rowIndices.is_null ()) {
this->template localGaussSeidel<ST, ST> (*B_in, *X_colMap, D,
dampingFactor,
KokkosClassic::Forward);
// mfh 18 Mar 2013: Aztec's implementation of "symmetric
// Gauss-Seidel" does _not_ do an Import between the forward
// and backward sweeps. This makes symmetric Gauss-Seidel a
// symmetric preconditioner if the matrix A is symmetric. We
// imitate Aztec's behavior here.
this->template localGaussSeidel<ST, ST> (*B_in, *X_colMap, D,
dampingFactor,
KokkosClassic::Backward);
}
else {
this->template reorderedLocalGaussSeidel<ST, ST> (*B_in, *X_colMap,
D, rowIndices,
dampingFactor,
KokkosClassic::Forward);
this->template reorderedLocalGaussSeidel<ST, ST> (*B_in, *X_colMap,
D, rowIndices,
dampingFactor,
KokkosClassic::Backward);
}
}
}
if (copyBackOutput) {
try {
deep_copy (X , *X_domainMap); // Copy result back into X.
} catch (std::exception& e) {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, prefix << "deep_copy(X, *X_domainMap) "
"threw an exception: " << e.what ());
}
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
template<class T>
Teuchos::RCP<CrsMatrix<T, LocalOrdinal, GlobalOrdinal, Node, classic> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
convert () const
{
using Teuchos::ArrayRCP;
using Teuchos::RCP;
using Teuchos::rcp;
typedef CrsMatrix<T, LocalOrdinal, GlobalOrdinal, Node, classic> out_mat_type;
typedef typename out_mat_type::local_matrix_type out_lcl_mat_type;
typedef typename out_lcl_mat_type::values_type out_vals_type;
typedef ArrayRCP<size_t>::size_type size_type;
const char tfecfFuncName[] = "convert";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isFillComplete (), std::runtime_error, "This matrix (the source of "
"the conversion) is not fill complete. You must first call "
"fillComplete() (possibly with the domain and range Map) without an "
"intervening call to resumeFill(), before you may call this method.");
// mfh 27 Feb 2014: It seems reasonable that if this matrix has a
// const graph, then the returned matrix should also. However, if
// this matrix does not have a const graph, then neither should
// the returned matrix. The code below implements this strategy.
RCP<out_mat_type> newmat; // the matrix to return
if (this->isStaticGraph ()) {
// This matrix has a const graph, so the returned matrix should too.
newmat = rcp (new out_mat_type (this->getCrsGraph ()));
// Convert the values from Scalar to T, and stuff them directly
// into the matrix to return.
const size_type numVals =
static_cast<size_type> (this->lclMatrix_.values.dimension_0 ());
// FIXME (mfh 05 Aug 2014) Write a copy kernel (impl_scalar_type and
// T differ, so we can't use Kokkos::deep_copy).
//
// FIXME (mfh 05 Aug 2014) This assumes UVM.
out_vals_type newVals1D ("Tpetra::CrsMatrix::val", numVals);
for (size_type k = 0; k < numVals; ++k) {
newVals1D(k) = static_cast<T> (this->k_values1D_(k));
}
newmat->lclMatrix_ =
out_lcl_mat_type ("Tpetra::CrsMatrix::lclMatrix_",
this->lclMatrix_.numCols (), newVals1D,
this->lclMatrix_.graph);
newmat->k_values1D_ = newVals1D;
// Since newmat has a static (const) graph, the graph already
// has a column Map, and Import and Export objects already exist
// (if applicable). Thus, calling fillComplete is cheap.
newmat->fillComplete (this->getDomainMap (), this->getRangeMap ());
}
else {
// This matrix has a nonconst graph, so the returned matrix
// should also have a nonconst graph. However, it's fine for
// the returned matrix to have static profile. This will
// certainly speed up its fillComplete.
//
// FIXME (mfh 05 Aug 2014) Instead of the slow stuff below, we
// should copy the values and existing graph into a new local
// matrix (lclMatrix), and then use the Tpetra::CrsMatrix
// constructor that takes (rowMap, colMap, lclMatrix, params).
//
// Get this matrix's local data.
ArrayRCP<const size_t> ptr;
ArrayRCP<const LocalOrdinal> ind;
ArrayRCP<const Scalar> oldVal;
this->getAllValues (ptr, ind, oldVal);
RCP<const map_type> rowMap = this->getRowMap ();
RCP<const map_type> colMap = this->getColMap ();
// Get an array of the number of entries in each (locally owned)
// row, so that we can make the new matrix with static profile.
const size_type numLocalRows =
static_cast<size_type> (rowMap->getNodeNumElements ());
ArrayRCP<size_t> numEntriesPerRow (numLocalRows);
for (size_type localRow = 0; localRow < numLocalRows; ++localRow) {
numEntriesPerRow[localRow] =
static_cast<size_type> (getNumEntriesInLocalRow (localRow));
}
newmat = rcp (new out_mat_type (rowMap, colMap, numEntriesPerRow,
StaticProfile));
// Convert this matrix's values from Scalar to T.
const size_type numVals = this->lclMatrix_.values.dimension_0 ();
ArrayRCP<T> newVals1D (numVals);
// FIXME (mfh 05 Aug 2014) This assumes UVM.
for (size_type k = 0; k < numVals; ++k) {
newVals1D[k] = static_cast<T> (this->k_values1D_(k));
}
// Give this matrix all of its local data. We can all this
// method because newmat was _not_ created with a const graph.
// The data must be passed in as nonconst, so we have to copy it
// first.
ArrayRCP<size_t> newPtr (ptr.size ());
std::copy (ptr.begin (), ptr.end (), newPtr.begin ());
ArrayRCP<LocalOrdinal> newInd (ind.size ());
std::copy (ind.begin (), ind.end (), newInd.begin ());
newmat->setAllValues (newPtr, newInd, newVals1D);
// We already have the Import and Export (if applicable) objects
// from the graph, so we can save a lot of time by passing them
// in to expertStaticFillComplete.
RCP<const map_type> domainMap = this->getDomainMap ();
RCP<const map_type> rangeMap = this->getRangeMap ();
RCP<const import_type> importer = this->getCrsGraph ()->getImporter ();
RCP<const export_type> exporter = this->getCrsGraph ()->getExporter ();
newmat->expertStaticFillComplete (domainMap, rangeMap, importer, exporter);
}
return newmat;
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
checkInternalState () const
{
#ifdef HAVE_TPETRA_DEBUG
const char tfecfFuncName[] = "checkInternalState: ";
const char err[] = "Internal state is not consistent. "
"Please report this bug to the Tpetra developers.";
// This version of the graph (RCP<const crs_graph_type>) must
// always be nonnull.
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
staticGraph_.is_null (),
std::logic_error, err);
// myGraph == null means that the matrix has a const ("static")
// graph. Otherwise, the matrix has a dynamic graph (it owns its
// graph).
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! myGraph_.is_null () && myGraph_ != staticGraph_,
std::logic_error, err);
// if matrix is fill complete, then graph must be fill complete
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
isFillComplete () && ! staticGraph_->isFillComplete (),
std::logic_error, err << " Specifically, the matrix is fill complete, "
"but its graph is NOT fill complete.");
// if matrix is storage optimized, it should have a 1D allocation
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
isStorageOptimized () && ! values2D_.is_null (),
std::logic_error, err);
// if matrix/graph are static profile, then 2D allocation should not be present
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
getProfileType() == StaticProfile && values2D_ != null,
std::logic_error, err);
// if matrix/graph are dynamic profile, then 1D allocation should not be present
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
getProfileType() == DynamicProfile && k_values1D_.dimension_0 () > 0,
std::logic_error, err);
// if values are allocated and they are non-zero in number, then
// one of the allocations should be present
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
staticGraph_->indicesAreAllocated () &&
staticGraph_->getNodeAllocationSize() > 0 &&
staticGraph_->getNodeNumRows() > 0
&& values2D_.is_null () &&
k_values1D_.dimension_0 () == 0,
std::logic_error, err);
// we cannot have both a 1D and 2D allocation
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
k_values1D_.dimension_0 () > 0 && values2D_ != null,
std::logic_error, err << " Specifically, k_values1D_ is allocated (has "
"size " << k_values1D_.dimension_0 () << " > 0) and values2D_ is also "
"allocated. CrsMatrix is not suppose to have both a 1-D and a 2-D "
"allocation at the same time.");
#endif
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
std::string
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
description () const
{
std::ostringstream os;
os << "Tpetra::CrsMatrix (Kokkos refactor): {";
if (this->getObjectLabel () != "") {
os << "Label: \"" << this->getObjectLabel () << "\", ";
}
if (isFillComplete ()) {
os << "isFillComplete: true"
<< ", global dimensions: [" << getGlobalNumRows () << ", "
<< getGlobalNumCols () << "]"
<< ", global number of entries: " << getGlobalNumEntries ()
<< "}";
}
else {
os << "isFillComplete: false"
<< ", global dimensions: [" << getGlobalNumRows () << ", "
<< getGlobalNumCols () << "]}";
}
return os.str ();
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
describe (Teuchos::FancyOStream &out,
const Teuchos::EVerbosityLevel verbLevel) const
{
using std::endl;
using std::setw;
using Teuchos::Comm;
using Teuchos::RCP;
using Teuchos::TypeNameTraits;
using Teuchos::VERB_DEFAULT;
using Teuchos::VERB_NONE;
using Teuchos::VERB_LOW;
using Teuchos::VERB_MEDIUM;
using Teuchos::VERB_HIGH;
using Teuchos::VERB_EXTREME;
const Teuchos::EVerbosityLevel vl = (verbLevel == VERB_DEFAULT) ? VERB_LOW : verbLevel;
if (vl == VERB_NONE) {
return; // Don't print anything at all
}
// By convention, describe() always begins with a tab.
Teuchos::OSTab tab0 (out);
RCP<const Comm<int> > comm = this->getComm();
const int myRank = comm->getRank();
const int numProcs = comm->getSize();
size_t width = 1;
for (size_t dec=10; dec<getGlobalNumRows(); dec *= 10) {
++width;
}
width = std::max<size_t> (width, static_cast<size_t> (11)) + 2;
// none: print nothing
// low: print O(1) info from node 0
// medium: print O(P) info, num entries per process
// high: print O(N) info, num entries per row
// extreme: print O(NNZ) info: print indices and values
//
// for medium and higher, print constituent objects at specified verbLevel
if (myRank == 0) {
out << "Tpetra::CrsMatrix (Kokkos refactor):" << endl;
}
Teuchos::OSTab tab1 (out);
if (myRank == 0) {
if (this->getObjectLabel () != "") {
out << "Label: \"" << this->getObjectLabel () << "\", ";
}
{
out << "Template parameters:" << endl;
Teuchos::OSTab tab2 (out);
out << "Scalar: " << TypeNameTraits<Scalar>::name () << endl
<< "LocalOrdinal: " << TypeNameTraits<LocalOrdinal>::name () << endl
<< "GlobalOrdinal: " << TypeNameTraits<GlobalOrdinal>::name () << endl
<< "Node: " << TypeNameTraits<Node>::name () << endl;
}
if (isFillComplete()) {
out << "isFillComplete: true" << endl
<< "Global dimensions: [" << getGlobalNumRows () << ", "
<< getGlobalNumCols () << "]" << endl
<< "Global number of entries: " << getGlobalNumEntries () << endl
<< "Global number of diagonal entries: " << getGlobalNumDiags ()
<< endl << "Global max number of entries in a row: "
<< getGlobalMaxNumRowEntries () << endl;
}
else {
out << "isFillComplete: false" << endl
<< "Global dimensions: [" << getGlobalNumRows () << ", "
<< getGlobalNumCols () << "]" << endl;
}
}
if (vl < VERB_MEDIUM) {
return; // all done!
}
// Describe the row Map.
if (myRank == 0) {
out << endl << "Row Map:" << endl;
}
if (getRowMap ().is_null ()) {
if (myRank == 0) {
out << "null" << endl;
}
}
else {
if (myRank == 0) {
out << endl;
}
getRowMap ()->describe (out, vl);
}
// Describe the column Map.
if (myRank == 0) {
out << "Column Map: ";
}
if (getColMap ().is_null ()) {
if (myRank == 0) {
out << "null" << endl;
}
} else if (getColMap () == getRowMap ()) {
if (myRank == 0) {
out << "same as row Map" << endl;
}
} else {
if (myRank == 0) {
out << endl;
}
getColMap ()->describe (out, vl);
}
// Describe the domain Map.
if (myRank == 0) {
out << "Domain Map: ";
}
if (getDomainMap ().is_null ()) {
if (myRank == 0) {
out << "null" << endl;
}
} else if (getDomainMap () == getRowMap ()) {
if (myRank == 0) {
out << "same as row Map" << endl;
}
} else if (getDomainMap () == getColMap ()) {
if (myRank == 0) {
out << "same as column Map" << endl;
}
} else {
if (myRank == 0) {
out << endl;
}
getDomainMap ()->describe (out, vl);
}
// Describe the range Map.
if (myRank == 0) {
out << "Range Map: ";
}
if (getRangeMap ().is_null ()) {
if (myRank == 0) {
out << "null" << endl;
}
} else if (getRangeMap () == getDomainMap ()) {
if (myRank == 0) {
out << "same as domain Map" << endl;
}
} else if (getRangeMap () == getRowMap ()) {
if (myRank == 0) {
out << "same as row Map" << endl;
}
} else {
if (myRank == 0) {
out << endl;
}
getRangeMap ()->describe (out, vl);
}
// O(P) data
for (int curRank = 0; curRank < numProcs; ++curRank) {
if (myRank == curRank) {
out << "Process rank: " << curRank << endl;
Teuchos::OSTab tab2 (out);
if (! staticGraph_->indicesAreAllocated ()) {
out << "Graph indices not allocated" << endl;
}
else {
out << "Number of allocated entries: "
<< staticGraph_->getNodeAllocationSize () << endl;
}
out << "Number of entries: " << getNodeNumEntries () << endl;
if (isFillComplete ()) {
out << "Number of diagonal entries: " << getNodeNumDiags () << endl;
}
out << "Max number of entries per row: " << getNodeMaxNumRowEntries ()
<< endl;
}
// Give output time to complete by executing some barriers.
comm->barrier ();
comm->barrier ();
comm->barrier ();
}
if (vl < VERB_HIGH) {
return; // all done!
}
// O(N) and O(NNZ) data
for (int curRank = 0; curRank < numProcs; ++curRank) {
if (myRank == curRank) {
out << std::setw(width) << "Proc Rank"
<< std::setw(width) << "Global Row"
<< std::setw(width) << "Num Entries";
if (vl == VERB_EXTREME) {
out << std::setw(width) << "(Index,Value)";
}
out << endl;
for (size_t r = 0; r < getNodeNumRows (); ++r) {
const size_t nE = getNumEntriesInLocalRow(r);
GlobalOrdinal gid = getRowMap()->getGlobalElement(r);
out << std::setw(width) << myRank
<< std::setw(width) << gid
<< std::setw(width) << nE;
if (vl == VERB_EXTREME) {
if (isGloballyIndexed()) {
ArrayView<const GlobalOrdinal> rowinds;
ArrayView<const Scalar> rowvals;
getGlobalRowView (gid, rowinds, rowvals);
for (size_t j = 0; j < nE; ++j) {
out << " (" << rowinds[j]
<< ", " << rowvals[j]
<< ") ";
}
}
else if (isLocallyIndexed()) {
ArrayView<const LocalOrdinal> rowinds;
ArrayView<const Scalar> rowvals;
getLocalRowView (r, rowinds, rowvals);
for (size_t j=0; j < nE; ++j) {
out << " (" << getColMap()->getGlobalElement(rowinds[j])
<< ", " << rowvals[j]
<< ") ";
}
} // globally or locally indexed
} // vl == VERB_EXTREME
out << endl;
} // for each row r on this process
} // if (myRank == curRank)
// Give output time to complete
comm->barrier ();
comm->barrier ();
comm->barrier ();
} // for each process p
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
checkSizes (const SrcDistObject& source)
{
// It's not clear what kind of compatibility checks on sizes can
// be performed here. Epetra_CrsGraph doesn't check any sizes for
// compatibility.
// Currently, the source object must be a RowMatrix with the same
// four template parameters as the target CrsMatrix. We might
// relax this requirement later.
typedef RowMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> row_matrix_type;
const row_matrix_type* srcRowMat =
dynamic_cast<const row_matrix_type*> (&source);
return (srcRowMat != NULL);
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
copyAndPermute (const SrcDistObject& source,
size_t numSameIDs,
const Teuchos::ArrayView<const LocalOrdinal>& permuteToLIDs,
const Teuchos::ArrayView<const LocalOrdinal>& permuteFromLIDs)
{
using Teuchos::Array;
using Teuchos::ArrayView;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef node_type NT;
// Method name string for TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC.
const char tfecfFuncName[] = "copyAndPermute: ";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
permuteToLIDs.size() != permuteFromLIDs.size(),
std::invalid_argument, "permuteToLIDs.size() = " << permuteToLIDs.size()
<< "!= permuteFromLIDs.size() = " << permuteFromLIDs.size() << ".");
// This dynamic cast should succeed, because we've already tested
// it in checkSizes().
typedef RowMatrix<Scalar, LO, GO, NT> row_matrix_type;
const row_matrix_type& srcMat = dynamic_cast<const row_matrix_type&> (source);
const bool sourceIsLocallyIndexed = srcMat.isLocallyIndexed ();
//
// Copy the first numSame row from source to target (this matrix).
// This involves copying rows corresponding to LIDs [0, numSame-1].
//
const map_type& srcRowMap = * (srcMat.getRowMap ());
Array<GO> rowInds;
Array<Scalar> rowVals;
const LO numSameIDs_as_LID = static_cast<LO> (numSameIDs);
for (LO sourceLID = 0; sourceLID < numSameIDs_as_LID; ++sourceLID) {
// Global ID for the current row index in the source matrix.
// The first numSameIDs GIDs in the two input lists are the
// same, so sourceGID == targetGID in this case.
const GO sourceGID = srcRowMap.getGlobalElement (sourceLID);
const GO targetGID = sourceGID;
// Input views for the combineGlobalValues() call below.
ArrayView<const GO> rowIndsConstView;
ArrayView<const Scalar> rowValsConstView;
if (sourceIsLocallyIndexed) {
const size_t rowLength = srcMat.getNumEntriesInGlobalRow (sourceGID);
if (rowLength > static_cast<size_t> (rowInds.size())) {
rowInds.resize (rowLength);
rowVals.resize (rowLength);
}
// Resizing invalidates an Array's views, so we must make new
// ones, even if rowLength hasn't changed.
ArrayView<GO> rowIndsView = rowInds.view (0, rowLength);
ArrayView<Scalar> rowValsView = rowVals.view (0, rowLength);
// The source matrix is locally indexed, so we have to get a
// copy. Really it's the GIDs that have to be copied (because
// they have to be converted from LIDs).
size_t checkRowLength = 0;
srcMat.getGlobalRowCopy (sourceGID, rowIndsView, rowValsView, checkRowLength);
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(rowLength != checkRowLength,
std::logic_error, "For global row index " << sourceGID << ", the source"
" matrix's getNumEntriesInGlobalRow() method returns a row length of "
<< rowLength << ", but the getGlobalRowCopy() method reports that "
"the row length is " << checkRowLength << ". Please report this bug "
"to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
rowIndsConstView = rowIndsView.view (0, rowLength);
rowValsConstView = rowValsView.view (0, rowLength);
}
else { // source matrix is globally indexed.
srcMat.getGlobalRowView (sourceGID, rowIndsConstView, rowValsConstView);
}
// Combine the data into the target matrix.
if (isStaticGraph()) {
// Applying a permutation to a matrix with a static graph
// means REPLACE-ing entries.
combineGlobalValues (targetGID, rowIndsConstView, rowValsConstView, REPLACE);
}
else {
// Applying a permutation to a matrix with a dynamic graph
// means INSERT-ing entries. This has the same effect as
// ADD, if the target graph already has an entry there.
combineGlobalValues (targetGID, rowIndsConstView, rowValsConstView, INSERT);
}
} // For each of the consecutive source and target IDs that are the same
//
// Permute the remaining rows.
//
const map_type& tgtRowMap = * (this->getRowMap ());
const size_t numPermuteToLIDs = static_cast<size_t> (permuteToLIDs.size ());
for (size_t p = 0; p < numPermuteToLIDs; ++p) {
const GO sourceGID = srcRowMap.getGlobalElement (permuteFromLIDs[p]);
const GO targetGID = tgtRowMap.getGlobalElement (permuteToLIDs[p]);
// Input views for the combineGlobalValues() call below.
ArrayView<const GO> rowIndsConstView;
ArrayView<const Scalar> rowValsConstView;
if (sourceIsLocallyIndexed) {
const size_t rowLength = srcMat.getNumEntriesInGlobalRow (sourceGID);
if (rowLength > static_cast<size_t> (rowInds.size ())) {
rowInds.resize (rowLength);
rowVals.resize (rowLength);
}
// Resizing invalidates an Array's views, so we must make new
// ones, even if rowLength hasn't changed.
ArrayView<GO> rowIndsView = rowInds.view (0, rowLength);
ArrayView<Scalar> rowValsView = rowVals.view (0, rowLength);
// The source matrix is locally indexed, so we have to get a
// copy. Really it's the GIDs that have to be copied (because
// they have to be converted from LIDs).
size_t checkRowLength = 0;
srcMat.getGlobalRowCopy (sourceGID, rowIndsView, rowValsView, checkRowLength);
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(rowLength != checkRowLength,
std::logic_error, "For the source matrix's global row index "
<< sourceGID << ", the source matrix's getNumEntriesInGlobalRow() "
"method returns a row length of " << rowLength << ", but the "
"getGlobalRowCopy() method reports that the row length is "
<< checkRowLength << ". Please report this bug to the Tpetra "
"developers.");
#endif // HAVE_TPETRA_DEBUG
rowIndsConstView = rowIndsView.view (0, rowLength);
rowValsConstView = rowValsView.view (0, rowLength);
}
else {
srcMat.getGlobalRowView (sourceGID, rowIndsConstView, rowValsConstView);
}
// Combine the data into the target matrix.
if (isStaticGraph()) {
this->combineGlobalValues (targetGID, rowIndsConstView,
rowValsConstView, REPLACE);
}
else {
this->combineGlobalValues (targetGID, rowIndsConstView,
rowValsConstView, INSERT);
}
} // For each ID to permute
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
packAndPrepare (const SrcDistObject& source,
const Teuchos::ArrayView<const LocalOrdinal>& exportLIDs,
Teuchos::Array<char>& exports,
const Teuchos::ArrayView<size_t>& numPacketsPerLID,
size_t& constantNumPackets,
Distributor& distor)
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
const char tfecfFuncName[] = "packAndPrepare: ";
// Attempt to cast the source object to RowMatrix. If the cast
// succeeds, use the source object's pack method to pack its data
// for communication. If the source object is really a CrsMatrix,
// this will pick up the CrsMatrix's more efficient override. If
// the RowMatrix cast fails, then the source object doesn't have
// the right type.
//
// FIXME (mfh 30 Jun 2013) We don't even need the RowMatrix to
// have the same Node type. Unfortunately, we don't have a way to
// ask if the RowMatrix is "a RowMatrix with any Node type," since
// RowMatrix doesn't have a base class. A hypothetical
// RowMatrixBase<Scalar, LO, GO> class, which does not currently
// exist, would satisfy this requirement.
//
// Why RowMatrixBase<Scalar, LO, GO>? The source object's Scalar
// type doesn't technically need to match the target object's
// Scalar type, so we could just have RowMatrixBase<LO, GO>. LO
// and GO need not be the same, as long as there is no overflow of
// the indices. However, checking for index overflow is global
// and therefore undesirable.
typedef RowMatrix<Scalar, LO, GO, Node> row_matrix_type;
const row_matrix_type* srcRowMat =
dynamic_cast<const row_matrix_type*> (&source);
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
srcRowMat == NULL, std::invalid_argument,
"The source object of the Import or Export operation is neither a "
"CrsMatrix (with the same template parameters as the target object), "
"nor a RowMatrix (with the same first four template parameters as the "
"target object).");
#ifdef HAVE_TPETRA_DEBUG
{
using Teuchos::reduceAll;
std::ostringstream msg;
int lclBad = 0;
try {
srcRowMat->pack (exportLIDs, exports, numPacketsPerLID,
constantNumPackets, distor);
} catch (std::exception& e) {
lclBad = 1;
msg << e.what ();
}
int gblBad = 0;
const Teuchos::Comm<int>& comm = * (this->getComm ());
reduceAll<int, int> (comm, Teuchos::REDUCE_MAX,
lclBad, Teuchos::outArg (gblBad));
if (gblBad != 0) {
const int myRank = comm.getRank ();
const int numProcs = comm.getSize ();
for (int r = 0; r < numProcs; ++r) {
if (r == myRank && lclBad != 0) {
std::ostringstream os;
os << "Proc " << myRank << ": " << msg.str () << std::endl;
std::cerr << os.str ();
}
comm.barrier ();
comm.barrier ();
comm.barrier ();
}
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::logic_error, "pack() threw an exception on one or "
"more participating processes.");
}
}
#else
srcRowMat->pack (exportLIDs, exports, numPacketsPerLID,
constantNumPackets, distor);
#endif // HAVE_TPETRA_DEBUG
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
packRow (char* const numEntOut,
char* const valOut,
char* const indOut,
const size_t numEnt,
const LocalOrdinal lclRow) const
{
using Teuchos::ArrayView;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
const LO numEntLO = static_cast<LO> (numEnt);
memcpy (numEntOut, &numEntLO, sizeof (LO));
if (this->isLocallyIndexed ()) {
// If the matrix is locally indexed on the calling process, we
// have to use its column Map (which it _must_ have in this
// case) to convert to global indices.
ArrayView<const LO> indIn;
ArrayView<const Scalar> valIn;
this->getLocalRowView (lclRow, indIn, valIn);
const map_type& colMap = * (this->getColMap ());
// Copy column indices one at a time, so that we don't need
// temporary storage.
for (size_t k = 0; k < numEnt; ++k) {
const GO gblIndIn = colMap.getGlobalElement (indIn[k]);
memcpy (indOut + k * sizeof (GO), &gblIndIn, sizeof (GO));
}
memcpy (valOut, valIn.getRawPtr (), numEnt * sizeof (Scalar));
}
else if (this->isGloballyIndexed ()) {
// If the matrix is globally indexed on the calling process,
// then we can use the column indices directly. However, we
// have to get the global row index. The calling process must
// have a row Map, since otherwise it shouldn't be participating
// in packing operations.
ArrayView<const GO> indIn;
ArrayView<const Scalar> valIn;
const map_type& rowMap = * (this->getRowMap ());
const GO gblRow = rowMap.getGlobalElement (lclRow);
this->getGlobalRowView (gblRow, indIn, valIn);
memcpy (indOut, indIn.getRawPtr (), numEnt * sizeof (GO));
memcpy (valOut, valIn.getRawPtr (), numEnt * sizeof (Scalar));
}
else {
if (numEnt != 0) {
return false;
}
}
return true;
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
bool
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
unpackRow (Scalar* const valInTmp,
GlobalOrdinal* const indInTmp,
const size_t tmpSize,
const char* const valIn,
const char* const indIn,
const size_t numEnt,
const LocalOrdinal lclRow,
const Tpetra::CombineMode combineMode)
{
if (tmpSize < numEnt || (numEnt != 0 && (valInTmp == NULL || indInTmp == NULL))) {
return false;
}
memcpy (valInTmp, valIn, numEnt * sizeof (Scalar));
memcpy (indInTmp, indIn, numEnt * sizeof (GlobalOrdinal));
const GlobalOrdinal gblRow = this->getRowMap ()->getGlobalElement (lclRow);
Teuchos::ArrayView<Scalar> val ((numEnt == 0) ? NULL : valInTmp, numEnt);
Teuchos::ArrayView<GlobalOrdinal> ind ((numEnt == 0) ? NULL : indInTmp, numEnt);
this->combineGlobalValues (gblRow, ind, val, combineMode);
return true;
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
allocatePackSpace (Teuchos::Array<char>& exports,
size_t& totalNumEntries,
const Teuchos::ArrayView<const LocalOrdinal>& exportLIDs) const
{
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef typename Teuchos::ArrayView<const LO>::size_type size_type;
//const char tfecfFuncName[] = "allocatePackSpace: ";
const size_type numExportLIDs = exportLIDs.size ();
// Count the total number of entries to send.
totalNumEntries = 0;
for (size_type i = 0; i < numExportLIDs; ++i) {
const LO lclRow = exportLIDs[i];
size_t curNumEntries = this->getNumEntriesInLocalRow (lclRow);
// FIXME (mfh 25 Jan 2015) We should actually report invalid row
// indices as an error. Just consider them nonowned for now.
if (curNumEntries == Teuchos::OrdinalTraits<size_t>::invalid ()) {
curNumEntries = 0;
}
totalNumEntries += curNumEntries;
}
// FIXME (mfh 24 Feb 2013) This code is only correct if
// sizeof(Scalar) is a meaningful representation of the amount of
// data in a Scalar instance. (LO and GO are always built-in
// integer types.)
//
// Allocate the exports array. It does NOT need padding for
// alignment, since we use memcpy to write to / read from send /
// receive buffers.
const size_t allocSize =
static_cast<size_t> (numExportLIDs) * sizeof (LO) +
totalNumEntries * (sizeof (Scalar) + sizeof (GO));
if (static_cast<size_t> (exports.size ()) < allocSize) {
exports.resize (allocSize);
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
pack (const Teuchos::ArrayView<const LocalOrdinal>& exportLIDs,
Teuchos::Array<char>& exports,
const Teuchos::ArrayView<size_t>& numPacketsPerLID,
size_t& constantNumPackets,
Distributor& distor) const
{
using Teuchos::Array;
using Teuchos::ArrayView;
using Teuchos::av_reinterpret_cast;
using Teuchos::RCP;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef typename ArrayView<const LO>::size_type size_type;
const char tfecfFuncName[] = "pack: ";
const size_type numExportLIDs = exportLIDs.size ();
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
numExportLIDs != numPacketsPerLID.size (), std::invalid_argument,
"exportLIDs.size() = " << numExportLIDs << " != numPacketsPerLID.size()"
" = " << numPacketsPerLID.size () << ".");
// Setting this to zero tells the caller to expect a possibly
// different ("nonconstant") number of packets per local index
// (i.e., a possibly different number of entries per row).
constantNumPackets = 0;
// The pack buffer 'exports' enters this method possibly
// unallocated. Do the first two parts of "Count, allocate, fill,
// compute."
size_t totalNumEntries = 0;
allocatePackSpace (exports, totalNumEntries, exportLIDs);
const size_t bufSize = static_cast<size_t> (exports.size ());
// Compute the number of "packets" (in this case, bytes) per
// export LID (in this case, local index of the row to send), and
// actually pack the data.
//
// FIXME (mfh 24 Feb 2013, 25 Jan 2015) This code is only correct
// if sizeof(Scalar) is a meaningful representation of the amount
// of data in a Scalar instance. (LO and GO are always built-in
// integer types.)
// Variables for error reporting in the loop.
size_type firstBadIndex = 0; // only valid if outOfBounds == true.
size_t firstBadOffset = 0; // only valid if outOfBounds == true.
size_t firstBadNumBytes = 0; // only valid if outOfBounds == true.
bool outOfBounds = false;
bool packErr = false;
char* const exportsRawPtr = exports.getRawPtr ();
size_t offset = 0; // current index into 'exports' array.
for (size_type i = 0; i < numExportLIDs; ++i) {
const LO lclRow = exportLIDs[i];
const size_t numEnt = this->getNumEntriesInLocalRow (lclRow);
// Only pad this row if it has a nonzero number of entries.
if (numEnt == 0) {
numPacketsPerLID[i] = 0;
}
else {
char* const numEntBeg = exportsRawPtr + offset;
char* const numEntEnd = numEntBeg + sizeof (LO);
char* const valBeg = numEntEnd;
char* const valEnd = valBeg + numEnt * sizeof (Scalar);
char* const indBeg = valEnd;
const size_t numBytes = sizeof (LO) +
numEnt * (sizeof (Scalar) + sizeof (GO));
if (offset > bufSize || offset + numBytes > bufSize) {
firstBadIndex = i;
firstBadOffset = offset;
firstBadNumBytes = numBytes;
outOfBounds = true;
break;
}
packErr = ! packRow (numEntBeg, valBeg, indBeg, numEnt, lclRow);
if (packErr) {
firstBadIndex = i;
firstBadOffset = offset;
firstBadNumBytes = numBytes;
break;
}
// numPacketsPerLID[i] is the number of "packets" in the
// current local row i. Packet=char (really "byte") so use
// the number of bytes of the packed data for that row.
numPacketsPerLID[i] = numBytes;
offset += numBytes;
}
}
TEUCHOS_TEST_FOR_EXCEPTION(
outOfBounds, std::logic_error, "First invalid offset into 'exports' "
"pack buffer at index i = " << firstBadIndex << ". exportLIDs[i]: "
<< exportLIDs[firstBadIndex] << ", bufSize: " << bufSize << ", offset: "
<< firstBadOffset << ", numBytes: " << firstBadNumBytes << ".");
TEUCHOS_TEST_FOR_EXCEPTION(
packErr, std::logic_error, "First error in packRow() at index i = "
<< firstBadIndex << ". exportLIDs[i]: " << exportLIDs[firstBadIndex]
<< ", bufSize: " << bufSize << ", offset: " << firstBadOffset
<< ", numBytes: " << firstBadNumBytes << ".");
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
combineGlobalValues (const GlobalOrdinal globalRowIndex,
const Teuchos::ArrayView<const GlobalOrdinal>& columnIndices,
const Teuchos::ArrayView<const Scalar>& values,
const Tpetra::CombineMode combineMode)
{
const char tfecfFuncName[] = "combineGlobalValues: ";
if (isStaticGraph ()) {
// INSERT doesn't make sense for a static graph, since you
// aren't allowed to change the structure of the graph.
// However, all the other combine modes work.
if (combineMode == ADD) {
sumIntoGlobalValues (globalRowIndex, columnIndices, values);
}
else if (combineMode == REPLACE) {
replaceGlobalValues (globalRowIndex, columnIndices, values);
}
else if (combineMode == ABSMAX) {
using Details::AbsMax;
AbsMax<Scalar> f;
this->template transformGlobalValues<AbsMax<Scalar> > (globalRowIndex,
columnIndices,
values, f);
}
else if (combineMode == INSERT) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
isStaticGraph () && combineMode == INSERT, std::invalid_argument,
"INSERT combine mode is not allowed if the matrix has a static graph "
"(i.e., was constructed with the CrsMatrix constructor that takes a "
"const CrsGraph pointer).");
}
else {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::logic_error, "Invalid combine mode; should never get "
"here! Please report this bug to the Tpetra developers.");
}
}
else { // The matrix has a dynamic graph.
if (combineMode == ADD || combineMode == INSERT) {
// For a dynamic graph, all incoming column indices are
// inserted into the target graph. Duplicate indices will
// have their values summed. In this context, ADD and INSERT
// are equivalent. We need to call insertGlobalValues()
// anyway if the column indices don't yet exist in this row,
// so we just call insertGlobalValues() for both cases.
insertGlobalValuesFiltered (globalRowIndex, columnIndices, values);
}
// FIXME (mfh 14 Mar 2012):
//
// Implementing ABSMAX or REPLACE for a dynamic graph would
// require modifying assembly to attach a possibly different
// combine mode to each inserted (i, j, A_ij) entry. For
// example, consider two different Export operations to the same
// target CrsMatrix, the first with ABSMAX combine mode and the
// second with REPLACE. This isn't a common use case, so we
// won't mess with it for now.
else if (combineMode == ABSMAX) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isStaticGraph () && combineMode == ABSMAX, std::logic_error,
"ABSMAX combine mode when the matrix has a dynamic graph is not yet "
"implemented.");
}
else if (combineMode == REPLACE) {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
! isStaticGraph () && combineMode == REPLACE, std::logic_error,
"REPLACE combine mode when the matrix has a dynamic graph is not yet "
"implemented.");
}
else {
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::logic_error, "Should never get here! Please report this "
"bug to the Tpetra developers.");
}
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
unpackAndCombine (const Teuchos::ArrayView<const LocalOrdinal>& importLIDs,
const Teuchos::ArrayView<const char>& imports,
const Teuchos::ArrayView<size_t>& numPacketsPerLID,
size_t constantNumPackets,
Distributor& distor,
CombineMode combineMode)
{
#ifdef HAVE_TPETRA_DEBUG
const char tfecfFuncName[] = "unpackAndCombine: ";
const CombineMode validModes[4] = {ADD, REPLACE, ABSMAX, INSERT};
const char* validModeNames[4] = {"ADD", "REPLACE", "ABSMAX", "INSERT"};
const int numValidModes = 4;
if (std::find (validModes, validModes+numValidModes, combineMode) ==
validModes+numValidModes) {
std::ostringstream os;
os << "Invalid combine mode. Valid modes are {";
for (int k = 0; k < numValidModes; ++k) {
os << validModeNames[k];
if (k < numValidModes - 1) {
os << ", ";
}
}
os << "}.";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::invalid_argument, os.str ());
}
{
using Teuchos::reduceAll;
std::ostringstream msg;
int lclBad = 0;
try {
this->unpackAndCombineImpl (importLIDs, imports, numPacketsPerLID,
constantNumPackets, distor, combineMode);
} catch (std::exception& e) {
lclBad = 1;
msg << e.what ();
}
int gblBad = 0;
const Teuchos::Comm<int>& comm = * (this->getComm ());
reduceAll<int, int> (comm, Teuchos::REDUCE_MAX,
lclBad, Teuchos::outArg (gblBad));
if (gblBad != 0) {
const int myRank = comm.getRank ();
const int numProcs = comm.getSize ();
for (int r = 0; r < numProcs; ++r) {
if (r == myRank && lclBad != 0) {
std::ostringstream os;
os << "Proc " << myRank << ": " << msg.str () << std::endl;
std::cerr << os.str ();
}
comm.barrier ();
comm.barrier ();
comm.barrier ();
}
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::logic_error, "unpackAndCombineImpl() threw an "
"exception on one or more participating processes.");
}
}
#else
this->unpackAndCombineImpl (importLIDs, imports, numPacketsPerLID,
constantNumPackets, distor, combineMode);
#endif // HAVE_TPETRA_DEBUG
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
unpackAndCombineImpl (const Teuchos::ArrayView<const LocalOrdinal>& importLIDs,
const Teuchos::ArrayView<const char>& imports,
const Teuchos::ArrayView<size_t>& numPacketsPerLID,
size_t constantNumPackets,
Distributor & /* distor */,
CombineMode combineMode)
{
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef typename Teuchos::ArrayView<const LO>::size_type size_type;
const char tfecfFuncName[] = "unpackAndCombine: ";
#ifdef HAVE_TPETRA_DEBUG
const CombineMode validModes[4] = {ADD, REPLACE, ABSMAX, INSERT};
const char* validModeNames[4] = {"ADD", "REPLACE", "ABSMAX", "INSERT"};
const int numValidModes = 4;
if (std::find (validModes, validModes+numValidModes, combineMode) ==
validModes+numValidModes) {
std::ostringstream os;
os << "Invalid combine mode. Valid modes are {";
for (int k = 0; k < numValidModes; ++k) {
os << validModeNames[k];
if (k < numValidModes - 1) {
os << ", ";
}
}
os << "}.";
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
true, std::invalid_argument, os.str ());
}
#endif // HAVE_TPETRA_DEBUG
const size_type numImportLIDs = importLIDs.size ();
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
numImportLIDs != numPacketsPerLID.size (), std::invalid_argument,
"importLIDs.size() = " << numImportLIDs << " != numPacketsPerLID.size()"
<< " = " << numPacketsPerLID.size () << ".");
// If a sanity check fails, keep track of some state at the
// "first" place where it fails. After the first failure, "run
// through the motions" until the end of this method, then raise
// an error with an informative message.
size_type firstBadIndex = 0;
size_t firstBadOffset = 0;
size_t firstBadExpectedNumBytes = 0;
size_t firstBadNumBytes = 0;
LO firstBadNumEnt = 0;
// We have sanity checks for three kinds of errors:
//
// 1. Offset into array of all the incoming data (for all rows)
// is out of bounds
// 2. Too few bytes of incoming data for a row, given the
// reported number of entries in those incoming data
// 3. Error in unpacking the row's incoming data
//
bool outOfBounds = false;
bool wrongNumBytes = false;
bool unpackErr = false;
const size_t bufSize = static_cast<size_t> (imports.size ());
const char* const importsRawPtr = imports.getRawPtr ();
size_t offset = 0;
// Temporary storage for incoming values and indices. We need
// this because the receive buffer does not align storage; it's
// just contiguous bytes. In order to avoid violating ANSI
// aliasing rules, we memcpy each incoming row's data into these
// temporary arrays. We double their size every time we run out
// of storage.
Array<Scalar> valInTmp;
Array<GO> indInTmp;
for (size_type i = 0; i < numImportLIDs; ++i) {
const LO lclRow = importLIDs[i];
const size_t numBytes = numPacketsPerLID[i];
if (numBytes > 0) { // there is actually something in the row
const char* const numEntBeg = importsRawPtr + offset;
const char* const numEntEnd = numEntBeg + sizeof (LO);
// Now we know how many entries to expect in the received data
// for this row.
LO numEnt = 0;
memcpy (&numEnt, numEntBeg, sizeof (LO));
const char* const valBeg = numEntEnd;
const char* const valEnd =
valBeg + static_cast<size_t> (numEnt) * sizeof (Scalar);
const char* const indBeg = valEnd;
const size_t expectedNumBytes = sizeof (LO) +
static_cast<size_t> (numEnt) * (sizeof (Scalar) + sizeof (GO));
if (expectedNumBytes > numBytes) {
firstBadIndex = i;
firstBadOffset = offset;
firstBadExpectedNumBytes = expectedNumBytes;
firstBadNumBytes = numBytes;
firstBadNumEnt = numEnt;
wrongNumBytes = true;
break;
}
if (offset > bufSize || offset + numBytes > bufSize) {
firstBadIndex = i;
firstBadOffset = offset;
firstBadExpectedNumBytes = expectedNumBytes;
firstBadNumBytes = numBytes;
firstBadNumEnt = numEnt;
outOfBounds = true;
break;
}
size_t tmpNumEnt = static_cast<size_t> (valInTmp.size ());
if (tmpNumEnt < static_cast<size_t> (numEnt) ||
static_cast<size_t> (indInTmp.size ()) < static_cast<size_t> (numEnt)) {
// Double the size of the temporary arrays for incoming data.
tmpNumEnt = std::max (static_cast<size_t> (numEnt), tmpNumEnt * 2);
valInTmp.resize (tmpNumEnt);
indInTmp.resize (tmpNumEnt);
}
unpackErr =
! unpackRow (valInTmp.getRawPtr (), indInTmp.getRawPtr (), tmpNumEnt,
valBeg, indBeg, numEnt, lclRow, combineMode);
if (unpackErr) {
firstBadIndex = i;
firstBadOffset = offset;
firstBadExpectedNumBytes = expectedNumBytes;
firstBadNumBytes = numBytes;
firstBadNumEnt = numEnt;
break;
}
offset += numBytes;
}
}
if (wrongNumBytes || outOfBounds || unpackErr) {
std::ostringstream os;
os << " importLIDs[i]: " << importLIDs[firstBadIndex]
<< ", bufSize: " << bufSize
<< ", offset: " << firstBadOffset
<< ", numBytes: " << firstBadNumBytes
<< ", expectedNumBytes: " << firstBadExpectedNumBytes
<< ", numEnt: " << firstBadNumEnt;
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
wrongNumBytes, std::logic_error, "At index i = " << firstBadIndex
<< ", expectedNumBytes > numBytes." << os.str ());
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
outOfBounds, std::logic_error, "First invalid offset into 'imports' "
"unpack buffer at index i = " << firstBadIndex << "." << os.str ());
TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
unpackErr, std::logic_error, "First error in unpackRow() at index i = "
<< firstBadIndex << "." << os.str ());
}
}
template<class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getColumnMapMultiVector (const MV& X_domainMap,
const bool force) const
{
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
TEUCHOS_TEST_FOR_EXCEPTION(
! this->hasColMap (), std::runtime_error, "Tpetra::CrsMatrix::getColumn"
"MapMultiVector: You may only call this method if the matrix has a "
"column Map. If the matrix does not yet have a column Map, you should "
"first call fillComplete (with domain and range Map if necessary).");
// If the graph is not fill complete, then the Import object (if
// one should exist) hasn't been constructed yet.
TEUCHOS_TEST_FOR_EXCEPTION(
! this->getGraph ()->isFillComplete (), std::runtime_error, "Tpetra::"
"CrsMatrix::getColumnMapMultiVector: You may only call this method if "
"this matrix's graph is fill complete.");
const size_t numVecs = X_domainMap.getNumVectors ();
RCP<const import_type> importer = this->getGraph ()->getImporter ();
RCP<const map_type> colMap = this->getColMap ();
RCP<MV> X_colMap; // null by default
// If the Import object is trivial (null), then we don't need a
// separate column Map multivector. Just return null in that
// case. The caller is responsible for knowing not to use the
// returned null pointer.
//
// If the Import is nontrivial, then we do need a separate
// column Map multivector for the Import operation. Check in
// that case if we have to (re)create the column Map
// multivector.
if (! importer.is_null () || force) {
if (importMV_.is_null () || importMV_->getNumVectors () != numVecs) {
X_colMap = rcp (new MV (colMap, numVecs));
// Cache the newly created multivector for later reuse.
importMV_ = X_colMap;
}
else { // Yay, we can reuse the cached multivector!
X_colMap = importMV_;
// mfh 09 Jan 2013: We don't have to fill with zeros first,
// because the Import uses INSERT combine mode, which overwrites
// existing entries.
//
//X_colMap->putScalar (ZERO);
}
}
return X_colMap;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
getRowMapMultiVector (const MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>& Y_rangeMap,
const bool force) const
{
using Teuchos::null;
using Teuchos::RCP;
using Teuchos::rcp;
// If the graph is not fill complete, then the Export object (if
// one should exist) hasn't been constructed yet.
TEUCHOS_TEST_FOR_EXCEPTION(
! this->getGraph ()->isFillComplete (), std::runtime_error, "Tpetra::"
"CrsMatrix::getRowMapMultiVector: You may only call this method if this "
"matrix's graph is fill complete.");
const size_t numVecs = Y_rangeMap.getNumVectors ();
RCP<const export_type> exporter = this->getGraph ()->getExporter ();
// Every version of the constructor takes either a row Map, or a
// graph (all of whose constructors take a row Map). Thus, the
// matrix always has a row Map.
RCP<const map_type> rowMap = this->getRowMap ();
RCP<MV> Y_rowMap; // null by default
// If the Export object is trivial (null), then we don't need a
// separate row Map multivector. Just return null in that case.
// The caller is responsible for knowing not to use the returned
// null pointer.
//
// If the Export is nontrivial, then we do need a separate row
// Map multivector for the Export operation. Check in that case
// if we have to (re)create the row Map multivector.
if (! exporter.is_null () || force) {
if (exportMV_.is_null () || exportMV_->getNumVectors () != numVecs) {
Y_rowMap = rcp (new MV (rowMap, numVecs));
exportMV_ = Y_rowMap; // Cache the newly created MV for later reuse.
}
else { // Yay, we can reuse the cached multivector!
Y_rowMap = exportMV_;
}
}
return Y_rowMap;
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
removeEmptyProcessesInPlace (const Teuchos::RCP<const map_type>& newMap)
{
TEUCHOS_TEST_FOR_EXCEPTION(
myGraph_.is_null (), std::logic_error, "Tpetra::CrsMatrix::"
"removeEmptyProcessesInPlace: This method does not work when the matrix "
"was created with a constant graph (that is, when it was created using "
"the version of its constructor that takes an RCP<const CrsGraph>). "
"This is because the matrix is not allowed to modify the graph in that "
"case, but removing empty processes requires modifying the graph.");
myGraph_->removeEmptyProcessesInPlace (newMap);
// Even though CrsMatrix's row Map (as returned by getRowMap())
// comes from its CrsGraph, CrsMatrix still implements DistObject,
// so we also have to change the DistObject's Map.
this->map_ = this->getRowMap ();
// In the nonconst graph case, staticGraph_ is just a const
// pointer to myGraph_. This assignment is probably redundant,
// but it doesn't hurt.
staticGraph_ = Teuchos::rcp_const_cast<const Graph> (myGraph_);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
Teuchos::RCP<RowMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
add (const Scalar& alpha,
const RowMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>& A,
const Scalar& beta,
const Teuchos::RCP<const map_type>& domainMap,
const Teuchos::RCP<const map_type>& rangeMap,
const Teuchos::RCP<Teuchos::ParameterList>& params) const
{
using Teuchos::Array;
using Teuchos::ArrayRCP;
using Teuchos::ParameterList;
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcp_implicit_cast;
using Teuchos::sublist;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef RowMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> row_matrix_type;
typedef CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> crs_matrix_type;
const crs_matrix_type& B = *this; // a convenient abbreviation
const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero ();
const Scalar ONE = Teuchos::ScalarTraits<Scalar>::one ();
// If the user didn't supply a domain or range Map, then try to
// get one from B first (if it has them), then from A (if it has
// them). If we don't have any domain or range Maps, scold the
// user.
RCP<const map_type> A_domainMap = A.getDomainMap ();
RCP<const map_type> A_rangeMap = A.getRangeMap ();
RCP<const map_type> B_domainMap = B.getDomainMap ();
RCP<const map_type> B_rangeMap = B.getRangeMap ();
RCP<const map_type> theDomainMap = domainMap;
RCP<const map_type> theRangeMap = rangeMap;
if (domainMap.is_null ()) {
if (B_domainMap.is_null ()) {
TEUCHOS_TEST_FOR_EXCEPTION(
A_domainMap.is_null (), std::invalid_argument,
"Tpetra::CrsMatrix::add: If neither A nor B have a domain Map, "
"then you must supply a nonnull domain Map to this method.");
theDomainMap = A_domainMap;
} else {
theDomainMap = B_domainMap;
}
}
if (rangeMap.is_null ()) {
if (B_rangeMap.is_null ()) {
TEUCHOS_TEST_FOR_EXCEPTION(
A_rangeMap.is_null (), std::invalid_argument,
"Tpetra::CrsMatrix::add: If neither A nor B have a range Map, "
"then you must supply a nonnull range Map to this method.");
theRangeMap = A_rangeMap;
} else {
theRangeMap = B_rangeMap;
}
}
#ifdef HAVE_TPETRA_DEBUG
// In a debug build, check that A and B have matching domain and
// range Maps, if they have domain and range Maps at all. (If
// they aren't fill complete, then they may not yet have them.)
if (! A_domainMap.is_null () && ! A_rangeMap.is_null ()) {
if (! B_domainMap.is_null () && ! B_rangeMap.is_null ()) {
TEUCHOS_TEST_FOR_EXCEPTION(
! B_domainMap->isSameAs (*A_domainMap), std::invalid_argument,
"Tpetra::CrsMatrix::add: The input RowMatrix A must have a domain Map "
"which is the same as (isSameAs) this RowMatrix's domain Map.");
TEUCHOS_TEST_FOR_EXCEPTION(
! B_rangeMap->isSameAs (*A_rangeMap), std::invalid_argument,
"Tpetra::CrsMatrix::add: The input RowMatrix A must have a range Map "
"which is the same as (isSameAs) this RowMatrix's range Map.");
TEUCHOS_TEST_FOR_EXCEPTION(
! domainMap.is_null () && ! domainMap->isSameAs (*B_domainMap),
std::invalid_argument,
"Tpetra::CrsMatrix::add: The input domain Map must be the same as "
"(isSameAs) this RowMatrix's domain Map.");
TEUCHOS_TEST_FOR_EXCEPTION(
! rangeMap.is_null () && ! rangeMap->isSameAs (*B_rangeMap),
std::invalid_argument,
"Tpetra::CrsMatrix::add: The input range Map must be the same as "
"(isSameAs) this RowMatrix's range Map.");
}
}
else if (! B_domainMap.is_null () && ! B_rangeMap.is_null ()) {
TEUCHOS_TEST_FOR_EXCEPTION(
! domainMap.is_null () && ! domainMap->isSameAs (*B_domainMap),
std::invalid_argument,
"Tpetra::CrsMatrix::add: The input domain Map must be the same as "
"(isSameAs) this RowMatrix's domain Map.");
TEUCHOS_TEST_FOR_EXCEPTION(
! rangeMap.is_null () && ! rangeMap->isSameAs (*B_rangeMap),
std::invalid_argument,
"Tpetra::CrsMatrix::add: The input range Map must be the same as "
"(isSameAs) this RowMatrix's range Map.");
}
else {
TEUCHOS_TEST_FOR_EXCEPTION(
domainMap.is_null () || rangeMap.is_null (), std::invalid_argument,
"Tpetra::CrsMatrix::add: If neither A nor B have a domain and range "
"Map, then you must supply a nonnull domain and range Map to this "
"method.");
}
#endif // HAVE_TPETRA_DEBUG
// What parameters do we pass to C's constructor? Do we call
// fillComplete on C after filling it? And if so, what parameters
// do we pass to C's fillComplete call?
bool callFillComplete = true;
RCP<ParameterList> constructorSublist;
RCP<ParameterList> fillCompleteSublist;
if (! params.is_null ()) {
callFillComplete = params->get ("Call fillComplete", callFillComplete);
constructorSublist = sublist (params, "Constructor parameters");
fillCompleteSublist = sublist (params, "fillComplete parameters");
}
RCP<const map_type> A_rowMap = A.getRowMap ();
RCP<const map_type> B_rowMap = B.getRowMap ();
RCP<const map_type> C_rowMap = B_rowMap; // see discussion in documentation
RCP<crs_matrix_type> C; // The result matrix.
// If A and B's row Maps are the same, we can compute an upper
// bound on the number of entries in each row of C, before
// actually computing the sum. A reasonable upper bound is the
// sum of the two entry counts in each row. If we choose this as
// the actual per-row upper bound, we can use static profile.
if (A_rowMap->isSameAs (*B_rowMap)) {
const LO localNumRows = static_cast<LO> (A_rowMap->getNodeNumElements ());
ArrayRCP<size_t> C_maxNumEntriesPerRow (localNumRows, 0);
// Get the number of entries in each row of A.
if (alpha != ZERO) {
for (LO localRow = 0; localRow < localNumRows; ++localRow) {
const size_t A_numEntries = A.getNumEntriesInLocalRow (localRow);
C_maxNumEntriesPerRow[localRow] += A_numEntries;
}
}
// Get the number of entries in each row of B.
if (beta != ZERO) {
for (LO localRow = 0; localRow < localNumRows; ++localRow) {
const size_t B_numEntries = B.getNumEntriesInLocalRow (localRow);
C_maxNumEntriesPerRow[localRow] += B_numEntries;
}
}
// Construct the result matrix C.
if (constructorSublist.is_null ()) {
C = rcp (new crs_matrix_type (C_rowMap, C_maxNumEntriesPerRow,
StaticProfile));
} else {
C = rcp (new crs_matrix_type (C_rowMap, C_maxNumEntriesPerRow,
StaticProfile, constructorSublist));
}
// Since A and B have the same row Maps, we could add them
// together all at once and merge values before we call
// insertGlobalValues. However, we don't really need to, since
// we've already allocated enough space in each row of C for C
// to do the merge itself.
}
else { // the row Maps of A and B are not the same
// Construct the result matrix C.
if (constructorSublist.is_null ()) {
C = rcp (new crs_matrix_type (C_rowMap, 0, DynamicProfile));
} else {
C = rcp (new crs_matrix_type (C_rowMap, 0, DynamicProfile,
constructorSublist));
}
}
#ifdef HAVE_TPETRA_DEBUG
TEUCHOS_TEST_FOR_EXCEPTION(C.is_null (), std::logic_error,
"Tpetra::RowMatrix::add: C should not be null at this point. "
"Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
//
// Compute C = alpha*A + beta*B.
//
Array<GO> ind;
Array<Scalar> val;
if (alpha != ZERO) {
const LO A_localNumRows = static_cast<LO> (A_rowMap->getNodeNumElements ());
for (LO localRow = 0; localRow < A_localNumRows; ++localRow) {
size_t A_numEntries = A.getNumEntriesInLocalRow (localRow);
const GO globalRow = A_rowMap->getGlobalElement (localRow);
if (A_numEntries > static_cast<size_t> (ind.size ())) {
ind.resize (A_numEntries);
val.resize (A_numEntries);
}
ArrayView<GO> indView = ind (0, A_numEntries);
ArrayView<Scalar> valView = val (0, A_numEntries);
A.getGlobalRowCopy (globalRow, indView, valView, A_numEntries);
if (alpha != ONE) {
for (size_t k = 0; k < A_numEntries; ++k) {
valView[k] *= alpha;
}
}
C->insertGlobalValues (globalRow, indView, valView);
}
}
if (beta != ZERO) {
const LO B_localNumRows = static_cast<LO> (B_rowMap->getNodeNumElements ());
for (LO localRow = 0; localRow < B_localNumRows; ++localRow) {
size_t B_numEntries = B.getNumEntriesInLocalRow (localRow);
const GO globalRow = B_rowMap->getGlobalElement (localRow);
if (B_numEntries > static_cast<size_t> (ind.size ())) {
ind.resize (B_numEntries);
val.resize (B_numEntries);
}
ArrayView<GO> indView = ind (0, B_numEntries);
ArrayView<Scalar> valView = val (0, B_numEntries);
B.getGlobalRowCopy (globalRow, indView, valView, B_numEntries);
if (beta != ONE) {
for (size_t k = 0; k < B_numEntries; ++k) {
valView[k] *= beta;
}
}
C->insertGlobalValues (globalRow, indView, valView);
}
}
if (callFillComplete) {
if (fillCompleteSublist.is_null ()) {
C->fillComplete (theDomainMap, theRangeMap);
} else {
C->fillComplete (theDomainMap, theRangeMap, fillCompleteSublist);
}
}
return rcp_implicit_cast<row_matrix_type> (C);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
transferAndFillComplete (Teuchos::RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> > & destMat,
const ::Tpetra::Details::Transfer<LocalOrdinal, GlobalOrdinal, Node>& rowTransfer,
const Teuchos::RCP<const map_type>& domainMap,
const Teuchos::RCP<const map_type>& rangeMap,
const Teuchos::RCP<Teuchos::ParameterList>& params) const
{
using Teuchos::ArrayView;
using Teuchos::Comm;
using Teuchos::ParameterList;
using Teuchos::RCP;
typedef LocalOrdinal LO;
typedef GlobalOrdinal GO;
typedef node_type NT;
typedef CrsMatrix<Scalar, LO, GO, NT> this_type;
typedef Vector<int, LO, GO, NT> IntVectorType;
#ifdef HAVE_TPETRA_MMM_TIMINGS
std::string label;
if(!params.is_null())
label = params->get("Timer Label",label);
std::string prefix = std::string("Tpetra ")+ label + std::string(": ");
using Teuchos::TimeMonitor;
Teuchos::RCP<Teuchos::TimeMonitor> MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC Pack-1"))));
#endif
// Make sure that the input argument rowTransfer is either an
// Import or an Export. Import and Export are the only two
// subclasses of Transfer that we defined, but users might
// (unwisely, for now at least) decide to implement their own
// subclasses. Exclude this possibility.
const import_type* xferAsImport = dynamic_cast<const import_type*> (&rowTransfer);
const export_type* xferAsExport = dynamic_cast<const export_type*> (&rowTransfer);
TEUCHOS_TEST_FOR_EXCEPTION(
xferAsImport == NULL && xferAsExport == NULL, std::invalid_argument,
"Tpetra::CrsMatrix::transferAndFillComplete: The 'rowTransfer' input "
"argument must be either an Import or an Export, and its template "
"parameters must match the corresponding template parameters of the "
"CrsMatrix.");
// FIXME (mfh 15 May 2014) Wouldn't communication still be needed,
// if the source Map is not distributed but the target Map is?
const bool communication_needed = rowTransfer.getSourceMap ()->isDistributed ();
//
// Get the caller's parameters
//
bool reverseMode = false; // Are we in reverse mode?
bool restrictComm = false; // Do we need to restrict the communicator?
RCP<ParameterList> matrixparams; // parameters for the destination matrix
if (! params.is_null ()) {
reverseMode = params->get ("Reverse Mode", reverseMode);
restrictComm = params->get ("Restrict Communicator", restrictComm);
matrixparams = sublist (params, "CrsMatrix");
}
// Get the new domain and range Maps. We need some of them for
// error checking, now that we have the reverseMode parameter.
RCP<const map_type> MyRowMap = reverseMode ?
rowTransfer.getSourceMap () : rowTransfer.getTargetMap ();
RCP<const map_type> MyColMap; // create this below
RCP<const map_type> MyDomainMap = ! domainMap.is_null () ?
domainMap : getDomainMap ();
RCP<const map_type> MyRangeMap = ! rangeMap.is_null () ?
rangeMap : getRangeMap ();
RCP<const map_type> BaseRowMap = MyRowMap;
RCP<const map_type> BaseDomainMap = MyDomainMap;
// If the user gave us a nonnull destMat, then check whether it's
// "pristine." That means that it has no entries.
//
// FIXME (mfh 15 May 2014) If this is not true on all processes,
// then this exception test may hang. It would be better to
// forward an error flag to the next communication phase.
if (! destMat.is_null ()) {
// FIXME (mfh 15 May 2014): The classic Petra idiom for checking
// whether a graph or matrix has no entries on the calling
// process, is that it is neither locally nor globally indexed.
// This may change eventually with the Kokkos refactor version
// of Tpetra, so it would be better just to check the quantity
// of interest directly. Note that with the Kokkos refactor
// version of Tpetra, asking for the total number of entries in
// a graph or matrix that is not fill complete might require
// computation (kernel launch), since it is not thread scalable
// to update a count every time an entry is inserted.
const bool NewFlag = ! destMat->getGraph ()->isLocallyIndexed () &&
! destMat->getGraph ()->isGloballyIndexed ();
TEUCHOS_TEST_FOR_EXCEPTION(
! NewFlag, std::invalid_argument, "Tpetra::CrsMatrix::"
"transferAndFillComplete: The input argument 'destMat' is only allowed "
"to be nonnull, if its graph is empty (neither locally nor globally "
"indexed).");
// FIXME (mfh 15 May 2014) At some point, we want to change
// graphs and matrices so that their DistObject Map
// (this->getMap()) may differ from their row Map. This will
// make redistribution for 2-D distributions more efficient. I
// hesitate to change this check, because I'm not sure how much
// the code here depends on getMap() and getRowMap() being the
// same.
TEUCHOS_TEST_FOR_EXCEPTION(
! destMat->getRowMap ()->isSameAs (*MyRowMap), std::invalid_argument,
"Tpetra::CrsMatrix::transferAndFillComplete: The (row) Map of the "
"input argument 'destMat' is not the same as the (row) Map specified "
"by the input argument 'rowTransfer'.");
TEUCHOS_TEST_FOR_EXCEPTION(
! destMat->checkSizes (*this), std::invalid_argument,
"Tpetra::CrsMatrix::transferAndFillComplete: You provided a nonnull "
"destination matrix, but checkSizes() indicates that it is not a legal "
"legal target for redistribution from the source matrix (*this). This "
"may mean that they do not have the same dimensions.");
}
// If forward mode (the default), then *this's (row) Map must be
// the same as the source Map of the Transfer. If reverse mode,
// then *this's (row) Map must be the same as the target Map of
// the Transfer.
//
// FIXME (mfh 15 May 2014) At some point, we want to change graphs
// and matrices so that their DistObject Map (this->getMap()) may
// differ from their row Map. This will make redistribution for
// 2-D distributions more efficient. I hesitate to change this
// check, because I'm not sure how much the code here depends on
// getMap() and getRowMap() being the same.
TEUCHOS_TEST_FOR_EXCEPTION(
! (reverseMode || getRowMap ()->isSameAs (*rowTransfer.getSourceMap ())),
std::invalid_argument, "Tpetra::CrsMatrix::transferAndFillComplete: "
"rowTransfer->getSourceMap() must match this->getRowMap() in forward mode.");
TEUCHOS_TEST_FOR_EXCEPTION(
! (! reverseMode || getRowMap ()->isSameAs (*rowTransfer.getTargetMap ())),
std::invalid_argument, "Tpetra::CrsMatrix::transferAndFillComplete: "
"rowTransfer->getTargetMap() must match this->getRowMap() in reverse mode.");
// The basic algorithm here is:
//
// 1. Call the moral equivalent of "distor.do" to handle the import.
// 2. Copy all the Imported and Copy/Permuted data into the raw
// CrsMatrix / CrsGraphData pointers, still using GIDs.
// 3. Call an optimized version of MakeColMap that avoids the
// Directory lookups (since the importer knows who owns all the
// GIDs) AND reindexes to LIDs.
// 4. Call expertStaticFillComplete()
// Get information from the Importer
const size_t NumSameIDs = rowTransfer.getNumSameIDs();
ArrayView<const LO> ExportLIDs = reverseMode ?
rowTransfer.getRemoteLIDs () : rowTransfer.getExportLIDs ();
ArrayView<const LO> RemoteLIDs = reverseMode ?
rowTransfer.getExportLIDs () : rowTransfer.getRemoteLIDs ();
ArrayView<const LO> PermuteToLIDs = reverseMode ?
rowTransfer.getPermuteFromLIDs () : rowTransfer.getPermuteToLIDs ();
ArrayView<const LO> PermuteFromLIDs = reverseMode ?
rowTransfer.getPermuteToLIDs () : rowTransfer.getPermuteFromLIDs ();
Distributor& Distor = rowTransfer.getDistributor ();
// Owning PIDs
Teuchos::Array<int> SourcePids;
Teuchos::Array<int> TargetPids;
int MyPID = getComm ()->getRank ();
// Temp variables for sub-communicators
RCP<const map_type> ReducedRowMap, ReducedColMap,
ReducedDomainMap, ReducedRangeMap;
RCP<const Comm<int> > ReducedComm;
// If the user gave us a null destMat, then construct the new
// destination matrix. We will replace its column Map later.
if (destMat.is_null ()) {
destMat = rcp (new this_type (MyRowMap, 0, StaticProfile, matrixparams));
}
/***************************************************/
/***** 1) First communicator restriction phase ****/
/***************************************************/
if (restrictComm) {
ReducedRowMap = MyRowMap->removeEmptyProcesses ();
ReducedComm = ReducedRowMap.is_null () ?
Teuchos::null :
ReducedRowMap->getComm ();
destMat->removeEmptyProcessesInPlace (ReducedRowMap);
ReducedDomainMap = MyRowMap.getRawPtr () == MyDomainMap.getRawPtr () ?
ReducedRowMap :
MyDomainMap->replaceCommWithSubset (ReducedComm);
ReducedRangeMap = MyRowMap.getRawPtr () == MyRangeMap.getRawPtr () ?
ReducedRowMap :
MyRangeMap->replaceCommWithSubset (ReducedComm);
// Reset the "my" maps
MyRowMap = ReducedRowMap;
MyDomainMap = ReducedDomainMap;
MyRangeMap = ReducedRangeMap;
// Update my PID, if we've restricted the communicator
if (! ReducedComm.is_null ()) {
MyPID = ReducedComm->getRank ();
}
else {
MyPID = -2; // For debugging
}
}
else {
ReducedComm = MyRowMap->getComm ();
}
/***************************************************/
/***** 2) From Tpera::DistObject::doTransfer() ****/
/***************************************************/
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC ImportSetup"))));
#endif
// Get the owning PIDs
RCP<const import_type> MyImporter = getGraph ()->getImporter ();
if (! restrictComm && ! MyImporter.is_null () &&
BaseDomainMap->isSameAs (*getDomainMap ())) {
// Same domain map as source matrix
//
// NOTE: This won't work for restrictComm (because the Import
// doesn't know the restricted PIDs), though writing an
// optimized version for that case would be easy (Import an
// IntVector of the new PIDs). Might want to add this later.
Import_Util::getPids (*MyImporter, SourcePids, false);
}
else if (MyImporter.is_null () && BaseDomainMap->isSameAs (*getDomainMap ())) {
// Matrix has no off-process entries
SourcePids.resize (getColMap ()->getNodeNumElements ());
SourcePids.assign (getColMap ()->getNodeNumElements (), MyPID);
}
else if (BaseDomainMap->isSameAs (*BaseRowMap) &&
getDomainMap ()->isSameAs (*getRowMap ())) {
// We can use the rowTransfer + SourceMatrix's Import to find out who owns what.
IntVectorType TargetRow_pids (domainMap);
IntVectorType SourceRow_pids (getRowMap ());
IntVectorType SourceCol_pids (getColMap ());
TargetRow_pids.putScalar (MyPID);
if (! reverseMode && xferAsImport != NULL) {
SourceRow_pids.doExport (TargetRow_pids, *xferAsImport, INSERT);
}
else if (reverseMode && xferAsExport != NULL) {
SourceRow_pids.doExport (TargetRow_pids, *xferAsExport, INSERT);
}
else if (! reverseMode && xferAsExport != NULL) {
SourceRow_pids.doImport (TargetRow_pids, *xferAsExport, INSERT);
}
else if (reverseMode && xferAsImport != NULL) {
SourceRow_pids.doImport (TargetRow_pids, *xferAsImport, INSERT);
}
else {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::logic_error, "Tpetra::CrsMatrix::"
"transferAndFillComplete: Should never get here! "
"Please report this bug to a Tpetra developer.");
}
SourceCol_pids.doImport (SourceRow_pids, *MyImporter, INSERT);
SourcePids.resize (getColMap ()->getNodeNumElements ());
SourceCol_pids.get1dCopy (SourcePids ());
}
else {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::invalid_argument, "Tpetra::CrsMatrix::"
"transferAndFillComplete: This method only allows either domainMap == "
"getDomainMap (), or (domainMap == rowTransfer.getTargetMap () and "
"getDomainMap () == getRowMap ()).");
}
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC Pack-2"))));
#endif
// Tpetra-specific stuff
//
// FIXME (mfh 15 May 2014) This should work fine if CrsMatrix
// inherits from DistObject (in which case all arrays that get
// resized here are Teuchos::Array), but it won't work if
// CrsMatrix inherits from DistObjectKA (in which case all arrays
// that get resized here are Kokkos::View). In the latter case,
// imports_ and numExportPacketsPerLID_ each have only a device
// view, but numImportPacketsPerLID_ has a device view and a host
// view (host_numImportPacketsPerLID_).
//
// Currently, CrsMatrix inherits from DistObject, not
// DistObjectKA, so the code below should be fine for the Kokkos
// refactor version of CrsMatrix.
//
// For this and for all other cases in this function that want to
// resize the DistObject's communication arrays, it would make
// sense to give DistObject (and DistObjectKA) methods for
// resizing that don't expose the details of whether these are
// Teuchos::Array or Kokkos::View.
size_t constantNumPackets = destMat->constantNumberOfPackets ();
if (constantNumPackets == 0) {
destMat->numExportPacketsPerLID_old_.resize (ExportLIDs.size ());
destMat->numImportPacketsPerLID_old_.resize (RemoteLIDs.size ());
}
else {
// There are a constant number of packets per element. We
// already know (from the number of "remote" (incoming)
// elements) how many incoming elements we expect, so we can
// resize the buffer accordingly.
const size_t rbufLen = RemoteLIDs.size() * constantNumPackets;
if (static_cast<size_t> (destMat->imports_old_.size ()) != rbufLen) {
destMat->imports_old_.resize (rbufLen);
}
}
// Pack & Prepare w/ owning PIDs
//
// FIXME (mfh 15 May 2014) This should work fine if CrsMatrix
// inherits from DistObject (in which case all arrays that get
// passed in here are Teuchos::Array), but it won't work if
// CrsMatrix inherits from DistObjectKA (in which case all arrays
// that get passed in here are Kokkos::View). In the latter case,
// exports_ and numExportPacketsPerLID_ each have only a device
// view.
//
// Currently, CrsMatrix inherits from DistObject, not
// DistObjectKA, so the code below should be fine for the Kokkos
// refactor version of CrsMatrix.
#ifdef HAVE_TPETRA_DEBUG
{
using Teuchos::outArg;
using Teuchos::REDUCE_MAX;
using Teuchos::reduceAll;
using std::cerr;
using std::endl;
RCP<const Teuchos::Comm<int> > comm = this->getComm ();
const int myRank = comm->getRank ();
const int numProcs = comm->getSize ();
std::ostringstream os;
int lclErr = 0;
try {
Import_Util::packAndPrepareWithOwningPIDs (*this, ExportLIDs,
destMat->exports_old_,
destMat->numExportPacketsPerLID_old_ (),
constantNumPackets, Distor,
SourcePids);
}
catch (std::exception& e) {
os << "Proc " << myRank << ": " << e.what ();
lclErr = 1;
}
int gblErr = 0;
if (! comm.is_null ()) {
reduceAll<int, int> (*comm, REDUCE_MAX, lclErr, outArg (gblErr));
}
if (gblErr != 0) {
if (myRank == 0) {
cerr << "packAndPrepareWithOwningPIDs threw an exception: " << endl;
}
std::ostringstream err;
for (int r = 0; r < numProcs; ++r) {
if (r == myRank && lclErr != 0) {
cerr << os.str () << endl;
}
comm->barrier ();
comm->barrier ();
comm->barrier ();
}
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::logic_error, "packAndPrepareWithOwningPIDs threw an "
"exception.");
}
}
#else
Import_Util::packAndPrepareWithOwningPIDs (*this, ExportLIDs,
destMat->exports_old_,
destMat->numExportPacketsPerLID_old_ (),
constantNumPackets, Distor,
SourcePids);
#endif // HAVE_TPETRA_DEBUG
// Do the exchange of remote data.
//
// FIXME (mfh 15 May 2014) This should work fine if CrsMatrix
// inherits from DistObject (in which case all arrays that get
// passed in here are Teuchos::Array), but it won't work if
// CrsMatrix inherits from DistObjectKA (in which case all arrays
// that get passed in here are Kokkos::View).
//
// In the latter case, imports_, exports_, and
// numExportPacketsPerLID_ each have only a device view.
// numImportPacketsPerLIDs_ is a device view, and also has a host
// view (host_numImportPacketsPerLID_).
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC Transfer"))));
#endif
if (communication_needed) {
if (reverseMode) {
if (constantNumPackets == 0) { // variable number of packets per LID
Distor.doReversePostsAndWaits (destMat->numExportPacketsPerLID_old_ ().getConst (), 1,
destMat->numImportPacketsPerLID_old_ ());
size_t totalImportPackets = 0;
for (Array_size_type i = 0; i < destMat->numImportPacketsPerLID_old_.size (); ++i) {
totalImportPackets += destMat->numImportPacketsPerLID_old_[i];
}
destMat->imports_old_.resize (totalImportPackets);
Distor.doReversePostsAndWaits (destMat->exports_old_ ().getConst (),
destMat->numExportPacketsPerLID_old_ (),
destMat->imports_old_ (),
destMat->numImportPacketsPerLID_old_ ());
}
else { // constant number of packets per LID
Distor.doReversePostsAndWaits (destMat->exports_old_ ().getConst (),
constantNumPackets,
destMat->imports_old_ ());
}
}
else { // forward mode (the default)
if (constantNumPackets == 0) { // variable number of packets per LID
Distor.doPostsAndWaits (destMat->numExportPacketsPerLID_old_ ().getConst (), 1,
destMat->numImportPacketsPerLID_old_ ());
size_t totalImportPackets = 0;
for (Array_size_type i = 0; i < destMat->numImportPacketsPerLID_old_.size (); ++i) {
totalImportPackets += destMat->numImportPacketsPerLID_old_[i];
}
destMat->imports_old_.resize (totalImportPackets);
Distor.doPostsAndWaits (destMat->exports_old_ ().getConst (),
destMat->numExportPacketsPerLID_old_ (),
destMat->imports_old_ (),
destMat->numImportPacketsPerLID_old_ ());
}
else { // constant number of packets per LID
Distor.doPostsAndWaits (destMat->exports_old_ ().getConst (),
constantNumPackets,
destMat->imports_old_ ());
}
}
}
/*********************************************************************/
/**** 3) Copy all of the Same/Permute/Remote data into CSR_arrays ****/
/*********************************************************************/
// FIXME (mfh 15 May 2014) This should work fine if CrsMatrix
// inherits from DistObject (in which case all arrays that get
// passed in here are Teuchos::Array), but it won't work if
// CrsMatrix inherits from DistObjectKA (in which case all arrays
// that get passed in here are Kokkos::View).
//
// In the latter case, imports_ only has a device view.
// numImportPacketsPerLIDs_ is a device view, and also has a host
// view (host_numImportPacketsPerLID_).
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC Unpack-1"))));
#endif
size_t mynnz =
Import_Util::unpackAndCombineWithOwningPIDsCount (*this, RemoteLIDs,
destMat->imports_old_ (),
destMat->numImportPacketsPerLID_old_ (),
constantNumPackets, Distor, INSERT,
NumSameIDs, PermuteToLIDs,
PermuteFromLIDs);
size_t N = BaseRowMap->getNodeNumElements ();
// Allocations
ArrayRCP<size_t> CSR_rowptr(N+1);
ArrayRCP<GO> CSR_colind_GID;
ArrayRCP<LO> CSR_colind_LID;
ArrayRCP<Scalar> CSR_vals;
CSR_colind_GID.resize (mynnz);
CSR_vals.resize (mynnz);
// If LO and GO are the same, we can reuse memory when
// converting the column indices from global to local indices.
if (typeid (LO) == typeid (GO)) {
CSR_colind_LID = Teuchos::arcp_reinterpret_cast<LO> (CSR_colind_GID);
}
else {
CSR_colind_LID.resize (mynnz);
}
// FIXME (mfh 15 May 2014) This should work fine if CrsMatrix
// inherits from DistObject (in which case all arrays that get
// passed in here are Teuchos::Array), but it won't work if
// CrsMatrix inherits from DistObjectKA (in which case all arrays
// that get passed in here are Kokkos::View).
//
// In the latter case, imports_ only has a device view.
// numImportPacketsPerLIDs_ is a device view, and also has a host
// view (host_numImportPacketsPerLID_).
//
// FIXME (mfh 15 May 2014) Why can't we abstract this out as an
// unpackAndCombine method on a "CrsArrays" object? This passing
// in a huge list of arrays is icky. Can't we have a bit of an
// abstraction? Implementing a concrete DistObject subclass only
// takes five methods.
Import_Util::unpackAndCombineIntoCrsArrays (*this, RemoteLIDs, destMat->imports_old_ (),
destMat->numImportPacketsPerLID_old_ (),
constantNumPackets, Distor, INSERT, NumSameIDs,
PermuteToLIDs, PermuteFromLIDs, N, mynnz, MyPID,
CSR_rowptr (), CSR_colind_GID (), CSR_vals (),
SourcePids (), TargetPids);
/**************************************************************/
/**** 4) Call Optimized MakeColMap w/ no Directory Lookups ****/
/**************************************************************/
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC Unpack-2"))));
#endif
// Call an optimized version of makeColMap that avoids the
// Directory lookups (since the Import object knows who owns all
// the GIDs).
Teuchos::Array<int> RemotePids;
Import_Util::lowCommunicationMakeColMapAndReindex (CSR_rowptr (),
CSR_colind_LID (),
CSR_colind_GID (),
BaseDomainMap,
TargetPids, RemotePids,
MyColMap);
/*******************************************************/
/**** 4) Second communicator restriction phase ****/
/*******************************************************/
if (restrictComm) {
ReducedColMap = (MyRowMap.getRawPtr () == MyColMap.getRawPtr ()) ?
ReducedRowMap :
MyColMap->replaceCommWithSubset (ReducedComm);
MyColMap = ReducedColMap; // Reset the "my" maps
}
// Replace the col map
destMat->replaceColMap (MyColMap);
// Short circuit if the processor is no longer in the communicator
//
// NOTE: Epetra replaces modifies all "removed" processes so they
// have a dummy (serial) Map that doesn't touch the original
// communicator. Duplicating that here might be a good idea.
if (ReducedComm.is_null ()) {
return;
}
/***************************************************/
/**** 5) Sort ****/
/***************************************************/
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC Unpack-3"))));
#endif
Import_Util::sortCrsEntries (CSR_rowptr (),
CSR_colind_LID (),
CSR_vals ());
if ((! reverseMode && xferAsImport != NULL) ||
(reverseMode && xferAsExport != NULL)) {
Import_Util::sortCrsEntries (CSR_rowptr (),
CSR_colind_LID (),
CSR_vals ());
}
else if ((! reverseMode && xferAsExport != NULL) ||
(reverseMode && xferAsImport != NULL)) {
Import_Util::sortAndMergeCrsEntries (CSR_rowptr (),
CSR_colind_LID (),
CSR_vals ());
if (CSR_rowptr[N] != mynnz) {
CSR_colind_LID.resize (CSR_rowptr[N]);
CSR_vals.resize (CSR_rowptr[N]);
}
}
else {
TEUCHOS_TEST_FOR_EXCEPTION(
true, std::logic_error, "Tpetra::CrsMatrix::"
"transferAndFillComplete: Should never get here! "
"Please report this bug to a Tpetra developer.");
}
/***************************************************/
/**** 6) Reset the colmap and the arrays ****/
/***************************************************/
// Call constructor for the new matrix (restricted as needed)
//
// NOTE (mfh 15 May 2014) This should work fine for the Kokkos
// refactor version of CrsMatrix, though it reserves the right to
// make a deep copy of the arrays.
destMat->setAllValues (CSR_rowptr, CSR_colind_LID, CSR_vals);
/***************************************************/
/**** 7) Build Importer & Call ESFC ****/
/***************************************************/
// Pre-build the importer using the existing PIDs
Teuchos::ParameterList esfc_params;
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC CreateImporter"))));
#endif
RCP<import_type> MyImport = rcp (new import_type (MyDomainMap, MyColMap, RemotePids));
#ifdef HAVE_TPETRA_MMM_TIMINGS
MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("TAFC ESFC"))));
esfc_params.set("Timer Label",prefix + std::string("TAFC"));
#endif
destMat->expertStaticFillComplete (MyDomainMap, MyRangeMap, MyImport,Teuchos::null,rcp(&esfc_params,false));
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
importAndFillComplete (Teuchos::RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> >& destMatrix,
const import_type& importer,
const Teuchos::RCP<const map_type>& domainMap,
const Teuchos::RCP<const map_type>& rangeMap,
const Teuchos::RCP<Teuchos::ParameterList>& params) const
{
transferAndFillComplete (destMatrix, importer, domainMap, rangeMap, params);
}
template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
void
CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic>::
exportAndFillComplete (Teuchos::RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, classic> >& destMatrix,
const export_type& exporter,
const Teuchos::RCP<const map_type>& domainMap,
const Teuchos::RCP<const map_type>& rangeMap,
const Teuchos::RCP<Teuchos::ParameterList>& params) const
{
transferAndFillComplete (destMatrix, exporter, domainMap, rangeMap, params);
}
} // namespace Tpetra
//
// Explicit instantiation macro
//
// Must be expanded from within the Tpetra namespace!
//
#define TPETRA_CRSMATRIX_MATRIX_INSTANT(SCALAR,LO,GO,NODE) \
\
template class CrsMatrix< SCALAR , LO , GO , NODE >; \
template RCP< CrsMatrix< SCALAR , LO , GO , NODE > > \
CrsMatrix< SCALAR , LO , GO , NODE >::convert< SCALAR > () const;
#define TPETRA_CRSMATRIX_CONVERT_INSTANT(SO,SI,LO,GO,NODE) \
\
template RCP< CrsMatrix< SO , LO , GO , NODE > > \
CrsMatrix< SI , LO , GO , NODE >::convert< SO > () const;
#define TPETRA_CRSMATRIX_IMPORT_AND_FILL_COMPLETE_INSTANT(SCALAR, LO, GO, NODE) \
template<> \
RCP<CrsMatrix<SCALAR, LO, GO, NODE> > \
importAndFillCompleteCrsMatrix (const RCP<const CrsMatrix<SCALAR, LO, GO, NODE> >& sourceMatrix, \
const Import<CrsMatrix<SCALAR, LO, GO, NODE>::local_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::global_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::node_type>& importer, \
const RCP<const Map<CrsMatrix<SCALAR, LO, GO, NODE>::local_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::global_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::node_type> >& domainMap, \
const RCP<const Map<CrsMatrix<SCALAR, LO, GO, NODE>::local_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::global_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::node_type> >& rangeMap, \
const RCP<Teuchos::ParameterList>& params);
#define TPETRA_CRSMATRIX_EXPORT_AND_FILL_COMPLETE_INSTANT(SCALAR, LO, GO, NODE) \
template<> \
RCP<CrsMatrix<SCALAR, LO, GO, NODE> > \
exportAndFillCompleteCrsMatrix (const RCP<const CrsMatrix<SCALAR, LO, GO, NODE> >& sourceMatrix, \
const Export<CrsMatrix<SCALAR, LO, GO, NODE>::local_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::global_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::node_type>& exporter, \
const RCP<const Map<CrsMatrix<SCALAR, LO, GO, NODE>::local_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::global_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::node_type> >& domainMap, \
const RCP<const Map<CrsMatrix<SCALAR, LO, GO, NODE>::local_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::global_ordinal_type, \
CrsMatrix<SCALAR, LO, GO, NODE>::node_type> >& rangeMap, \
const RCP<Teuchos::ParameterList>& params);
#define TPETRA_CRSMATRIX_INSTANT(SCALAR, LO, GO ,NODE) \
TPETRA_CRSMATRIX_MATRIX_INSTANT(SCALAR, LO, GO, NODE) \
TPETRA_CRSMATRIX_IMPORT_AND_FILL_COMPLETE_INSTANT(SCALAR, LO, GO, NODE) \
TPETRA_CRSMATRIX_EXPORT_AND_FILL_COMPLETE_INSTANT(SCALAR, LO, GO, NODE)
#endif // TPETRA_CRSMATRIX_DEF_HPP
|