This file is indexed.

/usr/include/trilinos/Tpetra_CrsGraph_def.hpp is in libtrilinos-tpetra-dev 12.10.1-3.

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
// @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_CRSGRAPH_DEF_HPP
#define TPETRA_CRSGRAPH_DEF_HPP

/// \file Tpetra_CrsGraph_def.hpp
/// \brief Definition of the Tpetra::CrsGraph class
///
/// If you want to use Tpetra::CrsGraph, include "Tpetra_CrsGraph.hpp"
/// (a file which CMake generates and installs for you).  If you only
/// want the declaration of Tpetra::CrsGraph, include
/// "Tpetra_CrsGraph_decl.hpp".

#include "Tpetra_Details_computeOffsets.hpp"
#include "Tpetra_Details_copyOffsets.hpp"
#include "Tpetra_Details_getGraphDiagOffsets.hpp"
#include "Tpetra_Distributor.hpp"
#include "Teuchos_SerialDenseMatrix.hpp"
#include <algorithm>
#include <limits>
#include <string>
#include <utility>

namespace Tpetra {
  namespace Details {
    namespace Impl {

      template<class LO, class GO, class DT, class OffsetType, class NumEntType>
      class ConvertColumnIndicesFromGlobalToLocal {
      public:
        ConvertColumnIndicesFromGlobalToLocal (const ::Kokkos::View<LO*, DT>& lclColInds,
                                               const ::Kokkos::View<const GO*, DT>& gblColInds,
                                               const ::Kokkos::View<const OffsetType*, DT>& ptr,
                                               const ::Tpetra::Details::LocalMap<LO, GO, DT>& lclColMap,
                                               const ::Kokkos::View<const NumEntType*, DT>& numRowEnt) :
          lclColInds_ (lclColInds),
          gblColInds_ (gblColInds),
          ptr_ (ptr),
          lclColMap_ (lclColMap),
          numRowEnt_ (numRowEnt)
        {}

        KOKKOS_FUNCTION void
        operator () (const LO& lclRow, OffsetType& curNumBad) const
        {
          const OffsetType offset = ptr_(lclRow);
          // NOTE (mfh 26 Jun 2016) It's always legal to cast the number
          // of entries in a row to LO, as long as the row doesn't have
          // too many duplicate entries.
          const LO numEnt = static_cast<LO> (numRowEnt_(lclRow));
          for (LO j = 0; j < numEnt; ++j) {
            const GO gid = gblColInds_(offset + j);
            const LO lid = lclColMap_.getLocalElement (gid);
            lclColInds_(offset + j) = lid;
            if (lid == ::Tpetra::Details::OrdinalTraits<LO>::invalid ()) {
              ++curNumBad;
            }
          }
        }

        static OffsetType
        run (const ::Kokkos::View<LO*, DT>& lclColInds,
             const ::Kokkos::View<const GO*, DT>& gblColInds,
             const ::Kokkos::View<const OffsetType*, DT>& ptr,
             const ::Tpetra::Details::LocalMap<LO, GO, DT>& lclColMap,
             const ::Kokkos::View<const NumEntType*, DT>& numRowEnt)
        {
          typedef ::Kokkos::RangePolicy<typename DT::execution_space, LO> range_type;
          typedef ConvertColumnIndicesFromGlobalToLocal<LO, GO, DT, OffsetType, NumEntType> functor_type;

          const LO lclNumRows = ptr.dimension_0 () == 0 ?
            static_cast<LO> (0) : static_cast<LO> (ptr.dimension_0 () - 1);
          OffsetType numBad = 0;
          // Count of "bad" column indices is a reduction over rows.
          ::Kokkos::parallel_reduce (range_type (0, lclNumRows),
                                     functor_type (lclColInds, gblColInds, ptr,
                                                   lclColMap, numRowEnt),
                                     numBad);
          return numBad;
        }

      private:
        ::Kokkos::View<LO*, DT> lclColInds_;
        ::Kokkos::View<const GO*, DT> gblColInds_;
        ::Kokkos::View<const OffsetType*, DT> ptr_;
        ::Tpetra::Details::LocalMap<LO, GO, DT> lclColMap_;
        ::Kokkos::View<const NumEntType*, DT> numRowEnt_;
      };

    } // namespace Impl

    /// \brief Convert a (StaticProfile) CrsGraph's global column
    ///   indices into local column indices.
    ///
    /// \param lclColInds [out] On output: The graph's local column
    ///   indices.  This may alias gblColInds, if LO == GO.
    /// \param gblColInds [in] On input: The graph's global column
    ///   indices.  This may alias lclColInds, if LO == GO.
    /// \param ptr [in] The graph's row offsets.
    /// \param lclColMap [in] "Local" (threaded-kernel-worthy) version
    ///   of the column Map.
    /// \param numRowEnt [in] Array with number of entries in each row.
    ///
    /// \return the number of "bad" global column indices (that don't
    ///   live in the column Map on the calling process).
    template<class LO, class GO, class DT, class OffsetType, class NumEntType>
    OffsetType
    convertColumnIndicesFromGlobalToLocal (const Kokkos::View<LO*, DT>& lclColInds,
                                           const Kokkos::View<const GO*, DT>& gblColInds,
                                           const Kokkos::View<const OffsetType*, DT>& ptr,
                                           const LocalMap<LO, GO, DT>& lclColMap,
                                           const Kokkos::View<const NumEntType*, DT>& numRowEnt)
    {
      using Impl::ConvertColumnIndicesFromGlobalToLocal;
      typedef ConvertColumnIndicesFromGlobalToLocal<LO, GO, DT, OffsetType, NumEntType> impl_type;
      return impl_type::run (lclColInds, gblColInds, ptr, lclColMap, numRowEnt);
    }

  } // namespace Details

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            size_t maxNumEntriesPerRow,
            ProfileType pftype,
            const Teuchos::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_ (rowMap)
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (pftype)
    , numAllocForAllRows_ (maxNumEntriesPerRow)
    , storageStatus_ (pftype == StaticProfile ?
                      Details::STORAGE_1D_UNPACKED :
                      Details::STORAGE_2D)
    , indicesAreAllocated_ (false)
    , indicesAreLocal_ (false)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    const char tfecfFuncName[] = "CrsGraph(rowMap,maxNumEntriesPerRow,"
      "pftype,params): ";
    staticAssertions ();
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      maxNumEntriesPerRow == Teuchos::OrdinalTraits<size_t>::invalid (),
      std::invalid_argument, "The allocation hint maxNumEntriesPerRow must be "
      "a valid size_t value, which in this case means it must not be "
      "Teuchos::OrdinalTraits<size_t>::invalid().");
    resumeFill (params);
    checkInternalState ();
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            const Teuchos::RCP<const map_type>& colMap,
            const size_t maxNumEntriesPerRow,
            const ProfileType pftype,
            const Teuchos::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_ (rowMap)
    , colMap_ (colMap)
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (pftype)
    , numAllocForAllRows_ (maxNumEntriesPerRow)
    , storageStatus_ (pftype == StaticProfile ?
                      Details::STORAGE_1D_UNPACKED :
                      Details::STORAGE_2D)
    , indicesAreAllocated_ (false)
    , indicesAreLocal_ (false)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    const char tfecfFuncName[] = "CrsGraph(rowMap,colMap,maxNumEntriesPerRow,"
      "pftype,params): ";
    staticAssertions ();
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      maxNumEntriesPerRow == Teuchos::OrdinalTraits<size_t>::invalid (),
      std::invalid_argument, "The allocation hint maxNumEntriesPerRow must be "
      "a valid size_t value, which in this case means it must not be "
      "Teuchos::OrdinalTraits<size_t>::invalid().");
    resumeFill (params);
    checkInternalState ();
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            const Teuchos::ArrayRCP<const size_t>& numEntPerRow,
            const ProfileType pftype,
            const Teuchos::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_ (rowMap)
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (pftype)
    , numAllocForAllRows_ (0)
    , storageStatus_ (pftype == StaticProfile ?
                      Details::STORAGE_1D_UNPACKED :
                      Details::STORAGE_2D)
    , indicesAreAllocated_ (false)
    , indicesAreLocal_ (false)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    const char tfecfFuncName[] = "CrsGraph(rowMap,numEntPerRow,pftype,params): ";
    staticAssertions ();

    const size_t lclNumRows = rowMap.is_null () ?
      static_cast<size_t> (0) : rowMap->getNodeNumElements ();
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (numEntPerRow.size ()) != lclNumRows,
      std::invalid_argument, "numEntPerRow has length " << numEntPerRow.size ()
      << " != the local number of rows " << lclNumRows << " as specified by "
      "the input row Map.");

#ifdef HAVE_TPETRA_DEBUG
    for (size_t r = 0; r < lclNumRows; ++r) {
      const size_t curRowCount = numEntPerRow[r];
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        curRowCount == Teuchos::OrdinalTraits<size_t>::invalid (),
        std::invalid_argument, "numEntPerRow(" << r << ") specifies an invalid "
        "number of entries (Teuchos::OrdinalTraits<size_t>::invalid()).");
    }
#endif // HAVE_TPETRA_DEBUG

    // Deep-copy the input (ArrayRCP, therefore host accessible) into
    // k_numAllocPerRow_.  The latter is a const View, so we have to
    // copy into a nonconst View first, then assign.
    typedef decltype (k_numAllocPerRow_) out_view_type;
    typedef typename out_view_type::non_const_type nc_view_type;
    typedef Kokkos::View<const size_t*,
                         typename nc_view_type::array_layout,
                         Kokkos::HostSpace,
                         Kokkos::MemoryUnmanaged> in_view_type;
    in_view_type numAllocPerRowIn (numEntPerRow.getRawPtr (), lclNumRows);
    nc_view_type numAllocPerRowOut ("Tpetra::CrsGraph::numAllocPerRow",
                                    lclNumRows);
    Kokkos::deep_copy (numAllocPerRowOut, numAllocPerRowIn);
    k_numAllocPerRow_ = numAllocPerRowOut;

    resumeFill (params);
    checkInternalState ();
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            const Kokkos::DualView<const size_t*, execution_space>& numEntPerRow,
            const ProfileType pftype,
            const Teuchos::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_ (rowMap)
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (pftype)
    , k_numAllocPerRow_ (numEntPerRow.h_view)
    , numAllocForAllRows_ (0)
    , storageStatus_ (pftype == StaticProfile ?
                      Details::STORAGE_1D_UNPACKED :
                      Details::STORAGE_2D)
    , indicesAreAllocated_ (false)
    , indicesAreLocal_ (false)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    const char tfecfFuncName[] = "CrsGraph(rowMap,numEntPerRow,pftype,params): ";
    staticAssertions ();

    const size_t lclNumRows = rowMap.is_null () ?
      static_cast<size_t> (0) : rowMap->getNodeNumElements ();
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (numEntPerRow.dimension_0 ()) != lclNumRows,
      std::invalid_argument, "numEntPerRow has length " <<
      numEntPerRow.dimension_0 () << " != the local number of rows " <<
      lclNumRows << " as specified by " "the input row Map.");

#ifdef HAVE_TPETRA_DEBUG
    for (size_t r = 0; r < lclNumRows; ++r) {
      const size_t curRowCount = numEntPerRow.h_view(r);
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        curRowCount == Teuchos::OrdinalTraits<size_t>::invalid (),
        std::invalid_argument, "numEntPerRow(" << r << ") specifies an invalid "
        "number of entries (Teuchos::OrdinalTraits<size_t>::invalid()).");
    }
#endif // HAVE_TPETRA_DEBUG

    resumeFill (params);
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            const Teuchos::RCP<const map_type>& colMap,
            const Kokkos::DualView<const size_t*, execution_space>& numEntPerRow,
            const ProfileType pftype,
            const Teuchos::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_ (rowMap)
    , colMap_ (colMap)
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (pftype)
    , k_numAllocPerRow_ (numEntPerRow.h_view)
    , numAllocForAllRows_ (0)
    , storageStatus_ (pftype == StaticProfile ?
                      Details::STORAGE_1D_UNPACKED :
                      Details::STORAGE_2D)
    , indicesAreAllocated_ (false)
    , indicesAreLocal_ (false)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    const char tfecfFuncName[] = "CrsGraph(rowMap,colMap,numEntPerRow,pftype,params): ";
    staticAssertions ();

    const size_t lclNumRows = rowMap.is_null () ?
      static_cast<size_t> (0) : rowMap->getNodeNumElements ();
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (numEntPerRow.dimension_0 ()) != lclNumRows,
      std::invalid_argument, "numEntPerRow has length " <<
      numEntPerRow.dimension_0 () << " != the local number of rows " <<
      lclNumRows << " as specified by " "the input row Map.");

#ifdef HAVE_TPETRA_DEBUG
    for (size_t r = 0; r < lclNumRows; ++r) {
      const size_t curRowCount = numEntPerRow.h_view(r);
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        curRowCount == Teuchos::OrdinalTraits<size_t>::invalid (),
        std::invalid_argument, "numEntPerRow(" << r << ") specifies an invalid "
        "number of entries (Teuchos::OrdinalTraits<size_t>::invalid()).");
    }
#endif // HAVE_TPETRA_DEBUG

    resumeFill (params);
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (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)
    , rowMap_ (rowMap)
    , colMap_ (colMap)
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (pftype)
    , numAllocForAllRows_ (0)
    , storageStatus_ (pftype == StaticProfile ?
                      Details::STORAGE_1D_UNPACKED :
                      Details::STORAGE_2D)
    , indicesAreAllocated_ (false)
    , indicesAreLocal_ (false)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    const char tfecfFuncName[] = "CrsGraph(rowMap,colMap,numEntPerRow,pftype,"
      "params): ";
    staticAssertions ();

    const size_t lclNumRows = rowMap.is_null () ?
      static_cast<size_t> (0) : rowMap->getNodeNumElements ();
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (numEntPerRow.size ()) != lclNumRows,
      std::invalid_argument, "numEntPerRow has length " << numEntPerRow.size ()
      << " != the local number of rows " << lclNumRows << " as specified by "
      "the input row Map.");

#ifdef HAVE_TPETRA_DEBUG
    for (size_t r = 0; r < lclNumRows; ++r) {
      const size_t curRowCount = numEntPerRow[r];
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        curRowCount == Teuchos::OrdinalTraits<size_t>::invalid (),
        std::invalid_argument, "numEntPerRow(" << r << ") specifies an invalid "
        "number of entries (Teuchos::OrdinalTraits<size_t>::invalid()).");
    }
#endif // HAVE_TPETRA_DEBUG

    // Deep-copy the input (ArrayRCP, therefore host accessible) into
    // k_numAllocPerRow_.  The latter is a const View, so we have to
    // copy into a nonconst View first, then assign.
    typedef decltype (k_numAllocPerRow_) out_view_type;
    typedef typename out_view_type::non_const_type nc_view_type;
    typedef Kokkos::View<const size_t*,
                         typename nc_view_type::array_layout,
                         Kokkos::HostSpace,
                         Kokkos::MemoryUnmanaged> in_view_type;
    in_view_type numAllocPerRowIn (numEntPerRow.getRawPtr (), lclNumRows);
    nc_view_type numAllocPerRowOut ("Tpetra::CrsGraph::numAllocPerRow",
                                    lclNumRows);
    Kokkos::deep_copy (numAllocPerRowOut, numAllocPerRowIn);
    k_numAllocPerRow_ = numAllocPerRowOut;

    resumeFill (params);
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            const Teuchos::RCP<const map_type>& colMap,
            const typename local_graph_type::row_map_type& rowPointers,
            const typename local_graph_type::entries_type::non_const_type& columnIndices,
            const Teuchos::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_(rowMap)
    , colMap_(colMap)
    , globalNumEntries_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , globalNumDiags_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , globalMaxNumRowEntries_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , nodeNumEntries_(0)
    , nodeNumAllocated_(Teuchos::OrdinalTraits<size_t>::invalid())
    , pftype_(StaticProfile)
    , numAllocForAllRows_(0)
    , storageStatus_ (Details::STORAGE_1D_PACKED)
    , indicesAreAllocated_(true)
    , indicesAreLocal_(true)
    , indicesAreGlobal_(false)
    , fillComplete_(false)
    , indicesAreSorted_(true)
    , noRedundancies_(true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_(true)
  {
    staticAssertions ();
    setAllIndices (rowPointers, columnIndices);
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (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::RCP<Teuchos::ParameterList>& params) :
    dist_object_type (rowMap)
    , rowMap_ (rowMap)
    , colMap_ (colMap)
    , globalNumEntries_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , globalNumDiags_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , globalMaxNumRowEntries_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , nodeNumEntries_ (0)
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (StaticProfile)
    , numAllocForAllRows_ (0)
    , storageStatus_ (Details::STORAGE_1D_PACKED)
    , indicesAreAllocated_ (true)
    , indicesAreLocal_ (true)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_ (true)
  {
    staticAssertions ();
    setAllIndices (rowPointers, columnIndices);
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  CrsGraph (const Teuchos::RCP<const map_type>& rowMap,
            const Teuchos::RCP<const map_type>& colMap,
            const local_graph_type& k_local_graph_,
            const Teuchos::RCP<Teuchos::ParameterList>& params)
    : DistObject<GlobalOrdinal, LocalOrdinal, GlobalOrdinal, node_type> (rowMap)
    , rowMap_ (rowMap)
    , colMap_ (colMap)
    , lclGraph_ (k_local_graph_)
    , globalNumEntries_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , globalNumDiags_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , globalMaxNumRowEntries_ (Teuchos::OrdinalTraits<global_size_t>::invalid ())
    , nodeNumEntries_ (0) // FIXME (mfh 17 Mar 2014) should get from lclGraph_ right now
    , nodeNumAllocated_ (Teuchos::OrdinalTraits<size_t>::invalid ())
    , pftype_ (StaticProfile)
    , numAllocForAllRows_ (0)
    , storageStatus_ (Details::STORAGE_1D_PACKED)
    , indicesAreAllocated_ (true)
    , indicesAreLocal_ (true)
    , indicesAreGlobal_ (false)
    , fillComplete_ (false)
    , indicesAreSorted_ (true)
    , noRedundancies_ (true)
    , haveLocalConstants_ (false)
    , haveGlobalConstants_ (false)
    , sortGhostsAssociatedWithEachProcessor_(true)
  {
    using Teuchos::arcp;
    using Teuchos::ArrayRCP;
    using Teuchos::ParameterList;
    using Teuchos::parameterList;
    using Teuchos::rcp;
    typedef GlobalOrdinal GO;
    typedef LocalOrdinal LO;

    staticAssertions();
    const char tfecfFuncName[] = "CrsGraph(Map,Map,Kokkos::LocalStaticCrsGraph)";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      colMap.is_null (), std::runtime_error,
      ": The input column Map must be nonnull.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      k_local_graph_.numRows () != rowMap->getNodeNumElements (),
      std::runtime_error,
      ": The input row Map and the input local graph need to have the same "
      "number of rows.  The row Map claims " << rowMap->getNodeNumElements ()
      << " row(s), but the local graph claims " << k_local_graph_.numRows ()
      << " row(s).");
    // NOTE (mfh 17 Mar 2014) getNodeNumRows() returns
    // rowMap_->getNodeNumElements(), but it doesn't have to.
    // TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
    //   k_local_graph_.numRows () != getNodeNumRows (), std::runtime_error,
    //   ": The input row Map and the input local graph need to have the same "
    //   "number of rows.  The row Map claims " << getNodeNumRows () << " row(s), "
    //   "but the local graph claims " << k_local_graph_.numRows () << " row(s).");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      k_lclInds1D_.dimension_0 () != 0 || k_gblInds1D_.dimension_0 () != 0, std::logic_error,
      ": cannot have 1D data structures allocated.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! lclInds2D_.is_null () || ! gblInds2D_.is_null (), std::logic_error,
      ": cannot have 2D data structures allocated.");

    nodeNumAllocated_ = k_local_graph_.row_map (getNodeNumRows ());
    nodeNumEntries_ = k_local_graph_.row_map (getNodeNumRows ());

    // NOTE (mfh 17 Mar 2014) We also need a version of this CrsGraph
    // constructor that takes a domain and range Map, as well as a row
    // and column Map.  In that case, we must pass the domain and
    // range Map into the following method.
    setDomainRangeMaps (rowMap_, rowMap_);
    makeImportExport ();

    k_lclInds1D_ = lclGraph_.entries;
    k_rowPtrs_ = lclGraph_.row_map;

    typename local_graph_type::row_map_type d_ptrs = lclGraph_.row_map;
    typename local_graph_type::entries_type d_inds = lclGraph_.entries;

    // Reset local properties
    upperTriangular_ = true;
    lowerTriangular_ = true;
    nodeMaxNumRowEntries_ = 0;
    nodeNumDiags_         = 0;

    // Compute triangular properties
    const size_t numLocalRows = getNodeNumRows ();
    for (size_t localRow = 0; localRow < numLocalRows; ++localRow) {
      const GO globalRow = rowMap_->getGlobalElement (localRow);
      const LO rlcid = colMap_->getLocalElement (globalRow);

      // It's entirely possible that the local matrix has no entries
      // in the column corresponding to the current row.  In that
      // case, the column Map may not necessarily contain that GID.
      // This is why we check whether rlcid is "invalid" (which means
      // that globalRow is not a GID in the column Map).
      if (rlcid != Teuchos::OrdinalTraits<LO>::invalid ()) {
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
          rlcid + 1 >= static_cast<LO> (d_ptrs.dimension_0 ()),
          std::runtime_error, ": The given row Map and/or column Map is/are "
          "not compatible with the provided local graph.");
        if (d_ptrs(rlcid) != d_ptrs(rlcid + 1)) {
          const size_t smallestCol =
            static_cast<size_t> (d_inds(d_ptrs(rlcid)));
          const size_t largestCol =
            static_cast<size_t> (d_inds(d_ptrs(rlcid + 1)-1));
          if (smallestCol < localRow) {
            upperTriangular_ = false;
          }
          if (localRow < largestCol) {
            lowerTriangular_ = false;
          }
          for (size_t i = d_ptrs(rlcid); i < d_ptrs(rlcid + 1); ++i) {
            if (d_inds(i) == rlcid) {
              ++nodeNumDiags_;
            }
          }
        }
        nodeMaxNumRowEntries_ =
          std::max (static_cast<size_t> (d_ptrs(rlcid + 1) - d_ptrs(rlcid)),
                    nodeMaxNumRowEntries_);
      }
    }

    haveLocalConstants_ = true;
    computeGlobalConstants ();

    fillComplete_ = true;
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  ~CrsGraph ()
  {}


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Teuchos::ParameterList>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getValidParameters () const
  {
    using Teuchos::RCP;
    using Teuchos::ParameterList;
    using Teuchos::parameterList;

    RCP<ParameterList> params = parameterList ("Tpetra::CrsGraph");

    // Make a sublist for the Import.
    RCP<ParameterList> importSublist = parameterList ("Import");

    // FIXME (mfh 02 Apr 2012) We should really have the Import and
    // Export objects fill in these lists.  However, we don't want to
    // create an Import or Export unless we need them.  For now, we
    // know that the Import and Export just pass the list directly to
    // their Distributor, so we can create a Distributor here
    // (Distributor's constructor is a lightweight operation) and have
    // it fill in the list.

    // Fill in Distributor default parameters by creating a
    // Distributor and asking it to do the work.
    Distributor distributor (rowMap_->getComm (), importSublist);
    params->set ("Import", *importSublist, "How the Import performs communication.");

    // Make a sublist for the Export.  For now, it's a clone of the
    // Import sublist.  It's not a shallow copy, though, since we
    // might like the Import to do communication differently than the
    // Export.
    params->set ("Export", *importSublist, "How the Export performs communication.");

    return params;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  setParameterList (const Teuchos::RCP<Teuchos::ParameterList>& params)
  {
    Teuchos::RCP<const Teuchos::ParameterList> validParams =
      getValidParameters ();
    params->validateParametersAndSetDefaults (*validParams);
    this->setMyParamList (params);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  global_size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalNumRows () const
  {
    return rowMap_->getGlobalNumElements ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  global_size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalNumCols () const
  {
    const char tfecfFuncName[] = "getGlobalNumCols: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! isFillComplete () || getDomainMap ().is_null (), std::runtime_error,
      "The graph does not have a domain Map.  You may not call this method in "
      "that case.");
    return getDomainMap ()->getGlobalNumElements ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeNumRows () const
  {
    return rowMap_.is_null () ? static_cast<size_t> (0) :
      rowMap_->getNodeNumElements ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeNumCols () const
  {
    const char tfecfFuncName[] = "getNodeNumCols: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasColMap (), std::runtime_error,
      "The graph does not have a column Map.  You may not call this method "
      "unless the graph has a column Map.  This requires either that a custom "
      "column Map was given to the constructor, or that fillComplete() has "
      "been called.");
    return colMap_.is_null () ? static_cast<size_t> (0) :
      colMap_->getNodeNumElements ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeNumDiags () const
  {
    return nodeNumDiags_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  global_size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalNumDiags () const
  {
    return globalNumDiags_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<Node>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNode () const
  {
    return rowMap_.is_null () ? Teuchos::null : rowMap_->getNode ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getRowMap () const
  {
    return rowMap_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getColMap () const
  {
    return colMap_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getDomainMap () const
  {
    return domainMap_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getRangeMap () const
  {
    return rangeMap_;
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Import<LocalOrdinal, GlobalOrdinal, Node> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getImporter () const
  {
    return importer_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Export<LocalOrdinal, GlobalOrdinal, Node> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getExporter () const
  {
    return exporter_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  hasColMap () const
  {
    return ! colMap_.is_null ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isStorageOptimized () const
  {
    // FIXME (mfh 07 Aug 2014) Why wouldn't storage be optimized if
    // getNodeNumRows() is zero?

    const bool isOpt = indicesAreAllocated_ &&
      k_numRowEntries_.dimension_0 () == 0 &&
      getNodeNumRows () > 0;

#ifdef HAVE_TPETRA_DEBUG
    const char tfecfFuncName[] = "isStorageOptimized";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isOpt && getProfileType () == DynamicProfile, std::logic_error,
      ": The matrix claims to have optimized storage, but getProfileType() "
      "returns DynamicProfile.  This should never happen.  Please report this "
      "bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG

    return isOpt;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  ProfileType
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getProfileType () const
  {
    return pftype_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  global_size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalNumEntries () const
  {
    return globalNumEntries_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeNumEntries () const
  {
    return nodeNumEntries_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  global_size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalMaxNumRowEntries () const
  {
    return globalMaxNumRowEntries_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeMaxNumRowEntries () const
  {
    return nodeMaxNumRowEntries_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isFillComplete () const
  {
    return fillComplete_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isFillActive () const
  {
    return ! fillComplete_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isUpperTriangular () const
  {
    return upperTriangular_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isLowerTriangular () const
  {
    return lowerTriangular_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isLocallyIndexed () const
  {
    return indicesAreLocal_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isGloballyIndexed () const
  {
    return indicesAreGlobal_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeAllocationSize () const
  {
    return nodeNumAllocated_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::RCP<const Teuchos::Comm<int> >
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getComm () const
  {
    return rowMap_.is_null () ? Teuchos::null : rowMap_->getComm ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  GlobalOrdinal
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getIndexBase () const
  {
    return rowMap_->getIndexBase ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  indicesAreAllocated () const
  {
    return indicesAreAllocated_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isSorted () const
  {
    return indicesAreSorted_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  isMerged () const
  {
    return noRedundancies_;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  setLocallyModified ()
  {
    // FIXME (mfh 07 May 2013) How do we know that the change
    // introduced a redundancy, or even that it invalidated the sorted
    // order of indices?  CrsGraph has always made this conservative
    // guess.  It could be a bit costly to check at insertion time,
    // though.
    indicesAreSorted_ = false;
    noRedundancies_ = false;

    // We've modified the graph, so we'll have to recompute local
    // constants like the number of diagonal entries on this process.
    haveLocalConstants_ = false;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  allocateIndices (const ELocalGlobal lg)
  {
    using Teuchos::arcp;
    using Teuchos::Array;
    using Teuchos::ArrayRCP;
    typedef Teuchos::ArrayRCP<size_t>::size_type size_type;
    typedef typename local_graph_type::row_map_type::non_const_type
      non_const_row_map_type;
    typedef typename local_graph_type::entries_type::non_const_type
      lcl_col_inds_type;
    typedef Kokkos::View<GlobalOrdinal*,
      typename lcl_col_inds_type::array_layout,
      device_type> gbl_col_inds_type;
    const char tfecfFuncName[] = "allocateIndices: ";

    // This is a protected function, only callable by us.  If it was
    // called incorrectly, it is our fault.  That's why the tests
    // below throw std::logic_error instead of std::invalid_argument.
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isLocallyIndexed () && lg == GlobalIndices, std::logic_error,
      "The graph is locally indexed, but Tpetra code is calling this method "
      "with lg=GlobalIndices.  Please report this bug to the Tpetra developers.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isGloballyIndexed () && lg == LocalIndices, std::logic_error,
      "The graph is globally indexed, but Tpetra code is calling this method "
      "with lg=LocalIndices.  Please report this bug to the Tpetra developers.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      indicesAreAllocated (), std::logic_error, "The graph's indices are "
      "already allocated, but Tpetra code is calling allocateIndices) again.  "
      "Please report this bug to the Tpetra developers.");

    const size_t numRows = getNodeNumRows ();

    if (getProfileType () == StaticProfile) {
      //
      //  STATIC ALLOCATION PROFILE
      //
      non_const_row_map_type k_rowPtrs ("Tpetra::CrsGraph::ptr", numRows + 1);

      if (k_numAllocPerRow_.dimension_0 () != 0) {
        // It's OK to throw std::invalid_argument here, because we
        // haven't incurred any side effects yet.  Throwing that
        // exception (and not, say, std::logic_error) implies that the
        // instance can recover.
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
          k_numAllocPerRow_.dimension_0 () != numRows, std::invalid_argument,
          "k_numAllocPerRow_ is allocated (has length != 0), but its length = "
          << k_numAllocPerRow_.dimension_0 () << " != numRows = " << numRows
          << ".");

        // k_numAllocPerRow_ is a host View, but k_rowPtrs (the thing
        // we want to compute here) lives on device.  That's OK;
        // computeOffsetsFromCounts can handle this case.
        using ::Tpetra::Details::computeOffsetsFromCounts;

        // FIXME (mfh 27 Jun 2016) Currently, computeOffsetsFromCounts
        // doesn't attempt to check its input for "invalid" flag
        // values.  For now, we omit that feature of the sequential
        // code disabled below.
        computeOffsetsFromCounts (k_rowPtrs, k_numAllocPerRow_);
      }
      else {
        // It's OK to throw std::invalid_argument here, because we
        // haven't incurred any side effects yet.  Throwing that
        // exception (and not, say, std::logic_error) implies that the
        // instance can recover.
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (numAllocForAllRows_ == Teuchos::OrdinalTraits<size_t>::invalid (),
           std::invalid_argument, "numAllocForAllRows_ has an invalid value, "
           "namely Teuchos::OrdinalTraits<size_t>::invalid() = " <<
           Teuchos::OrdinalTraits<size_t>::invalid () << ".");

        using ::Tpetra::Details::computeOffsetsFromConstantCount;
        computeOffsetsFromConstantCount (k_rowPtrs, numAllocForAllRows_);
      }

      // "Commit" the resulting row offsets.
      k_rowPtrs_ = k_rowPtrs;

      // FIXME (mfh 05,11 Aug 2014) This assumes UVM, since k_rowPtrs_
      // is currently a device View.  Should instead use a DualView.
      const size_type numInds = static_cast<size_type> (k_rowPtrs_(numRows));
      if (lg == LocalIndices) {
        k_lclInds1D_ = lcl_col_inds_type ("Tpetra::CrsGraph::ind", numInds);
      }
      else {
        k_gblInds1D_ = gbl_col_inds_type ("Tpetra::CrsGraph::ind", numInds);
      }
      nodeNumAllocated_ = numInds;
      storageStatus_ = Details::STORAGE_1D_UNPACKED;
    }
    else {
      //
      //  DYNAMIC ALLOCATION PROFILE
      //

      const bool useNumAllocPerRow = (k_numAllocPerRow_.dimension_0 () != 0);

      if (lg == LocalIndices) {
        lclInds2D_ = arcp<Array<LocalOrdinal> > (numRows);
        nodeNumAllocated_ = 0;
        for (size_t i = 0; i < numRows; ++i) {
          const size_t howMany = useNumAllocPerRow ?
            k_numAllocPerRow_(i) : numAllocForAllRows_;
          nodeNumAllocated_ += howMany;
          if (howMany > 0) {
            lclInds2D_[i].resize (howMany);
          }
        }
      }
      else { // allocate global indices
        gblInds2D_ = arcp<Array<GlobalOrdinal> > (numRows);
        nodeNumAllocated_ = 0;
        for (size_t i = 0; i < numRows; ++i) {
          const size_t howMany = useNumAllocPerRow ?
            k_numAllocPerRow_(i) : numAllocForAllRows_;
          nodeNumAllocated_ += howMany;
          if (howMany > 0) {
            gblInds2D_[i].resize (howMany);
          }
        }
      }
      storageStatus_ = Details::STORAGE_2D;
    }

    indicesAreLocal_  = (lg == LocalIndices);
    indicesAreGlobal_ = (lg == GlobalIndices);

    if (numRows > 0) { // reallocate k_numRowEntries_ & fill w/ 0s
      using Kokkos::ViewAllocateWithoutInitializing;
      typedef decltype (k_numRowEntries_) row_ent_type;
      const char label[] = "Tpetra::CrsGraph::numRowEntries";

      row_ent_type numRowEnt (ViewAllocateWithoutInitializing (label), numRows);
      Kokkos::deep_copy (numRowEnt, static_cast<size_t> (0)); // fill w/ 0s
      k_numRowEntries_ = numRowEnt; // "commit" our allocation
    }

    // done with these
    numAllocForAllRows_ = 0;
    k_numAllocPerRow_ = decltype (k_numAllocPerRow_) ();
    indicesAreAllocated_ = true;
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::ArrayView<const LocalOrdinal>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalView (const RowInfo rowinfo) const
  {
    using Kokkos::subview;
    typedef LocalOrdinal LO;
    typedef Kokkos::View<const LO*, execution_space,
      Kokkos::MemoryUnmanaged> row_view_type;

    if (rowinfo.allocSize == 0) {
      return Teuchos::ArrayView<const LO> ();
    }
    else { // nothing in the row to view
      if (k_lclInds1D_.dimension_0 () != 0) { // 1-D storage
        const size_t start = rowinfo.offset1D;
        const size_t len = rowinfo.allocSize;
        const std::pair<size_t, size_t> rng (start, start + len);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_lclInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        row_view_type rowView = subview (row_view_type (k_lclInds1D_), rng);
        const LO* const rowViewRaw = (len == 0) ? NULL : rowView.ptr_on_device ();
        return Teuchos::ArrayView<const LO> (rowViewRaw, len, Teuchos::RCP_DISABLE_NODE_LOOKUP);
      }
      else if (! lclInds2D_[rowinfo.localRow].empty ()) { // 2-D storage
        return lclInds2D_[rowinfo.localRow] ();
      }
      else {
        return Teuchos::ArrayView<const LO> (); // nothing in the row to view
      }
    }
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  LocalOrdinal
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalViewRawConst (const LocalOrdinal*& lclInds,
                        LocalOrdinal& numEnt,
                        const RowInfo& rowinfo) const
  {
    lclInds = NULL;
    numEnt = 0;

    if (rowinfo.allocSize != 0) {
      if (k_lclInds1D_.dimension_0 () != 0) { // 1-D storage
#ifdef HAVE_TPETRA_DEBUG
        if (rowinfo.offset1D + rowinfo.allocSize >
            static_cast<size_t> (k_lclInds1D_.dimension_0 ())) {
          return static_cast<LocalOrdinal> (-1);
        }
#endif // HAVE_TPETRA_DEBUG
        lclInds = &k_lclInds1D_[rowinfo.offset1D];
        numEnt = rowinfo.allocSize;
      }
      else { // 2-D storage
#ifdef HAVE_TPETRA_DEBUG
        if (rowinfo.localRow >= static_cast<size_t> (lclInds2D_.size ())) {
          return static_cast<LocalOrdinal> (-1);
        }
#endif // HAVE_TPETRA_DEBUG
        // Use a const reference so we don't touch the ArrayRCP's ref
        // count, since ArrayRCP's ref count is not thread safe.
        const auto& curRow = lclInds2D_[rowinfo.localRow];
        if (! curRow.empty ()) {
          lclInds = curRow.getRawPtr ();
          numEnt = curRow.size ();
        }
      }
    }
    return static_cast<LocalOrdinal> (0);
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::ArrayView<LocalOrdinal>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalViewNonConst (const RowInfo rowinfo)
  {
    using Kokkos::subview;
    typedef LocalOrdinal LO;
    typedef Kokkos::View<LO*, execution_space,
      Kokkos::MemoryUnmanaged> row_view_type;

    if (rowinfo.allocSize == 0) { // nothing in the row to view
      return Teuchos::ArrayView<LO> ();
    }
    else {
      if (k_lclInds1D_.dimension_0 () != 0) { // 1-D storage
        const size_t start = rowinfo.offset1D;
        const size_t len = rowinfo.allocSize;
        const std::pair<size_t, size_t> rng (start, start + len);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_lclInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        row_view_type rowView = subview (row_view_type (k_lclInds1D_), rng);
        LO* const rowViewRaw = (len == 0) ? NULL : rowView.ptr_on_device ();
        return Teuchos::ArrayView<LO> (rowViewRaw, len, Teuchos::RCP_DISABLE_NODE_LOOKUP);
      }
      else if (! lclInds2D_[rowinfo.localRow].empty ()) { // 2-D storage
        return lclInds2D_[rowinfo.localRow] ();
      }
      else {
        return Teuchos::ArrayView<LO> (); // nothing in the row to view
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Kokkos::View<const LocalOrdinal*,
               typename CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::execution_space,
               Kokkos::MemoryUnmanaged>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalKokkosRowView (const RowInfo& rowinfo) const
  {
    typedef LocalOrdinal LO;
    typedef Kokkos::View<const LO*, execution_space,
      Kokkos::MemoryUnmanaged> row_view_type;

    if (rowinfo.allocSize == 0) {
      return row_view_type ();
    }
    else { // nothing in the row to view
      if (k_lclInds1D_.dimension_0 () != 0) { // 1-D storage
        const size_t start = rowinfo.offset1D;
        const size_t len = rowinfo.allocSize;
        const std::pair<size_t, size_t> rng (start, start + len);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_lclInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        return Kokkos::subview (row_view_type (k_lclInds1D_), rng);
      }
      else if (! lclInds2D_[rowinfo.localRow].empty ()) { // 2-D storage
        // Use a reference, to avoid doing the array lookup twice.
        //
        // NOTE (mfh 18 Jul 2016) Don't create a Teuchos::ArrayView,
        // because this is not thread safe in a debug build.
        Teuchos::Array<LocalOrdinal>& lclInds = lclInds2D_[rowinfo.localRow];
        const LO* rowPtr = lclInds.getRawPtr ();
        const auto rowSize = lclInds.size ();
        return row_view_type (rowPtr, rowSize);
      }
      else {
        return row_view_type (); // nothing in the row to view
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Kokkos::View<LocalOrdinal*,
               typename CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::execution_space,
               Kokkos::MemoryUnmanaged>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalKokkosRowViewNonConst (const RowInfo& rowinfo)
  {
    typedef LocalOrdinal LO;
    typedef Kokkos::View<LO*, execution_space,
      Kokkos::MemoryUnmanaged> row_view_type;

    if (rowinfo.allocSize == 0) {
      return row_view_type ();
    }
    else { // nothing in the row to view
      if (k_lclInds1D_.dimension_0 () != 0) { // 1-D storage
        const size_t start = rowinfo.offset1D;
        const size_t len = rowinfo.allocSize;
        const std::pair<size_t, size_t> rng (start, start + len);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_lclInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        return Kokkos::subview (row_view_type (k_lclInds1D_), rng);
      }
      else if (! lclInds2D_[rowinfo.localRow].empty ()) { // 2-D storage
        Teuchos::ArrayView<LO> rowAv = lclInds2D_[rowinfo.localRow] ();
        return row_view_type (rowAv.getRawPtr (), rowAv.size ());
      }
      else {
        return row_view_type (); // nothing in the row to view
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Kokkos::View<const GlobalOrdinal*,
               typename CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::execution_space,
               Kokkos::MemoryUnmanaged>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalKokkosRowView (const RowInfo& rowinfo) const
  {
    typedef GlobalOrdinal GO;
    typedef Kokkos::View<const GO*, execution_space,
      Kokkos::MemoryUnmanaged> row_view_type;

    if (rowinfo.allocSize == 0) {
      return row_view_type ();
    }
    else { // nothing in the row to view
      if (this->k_gblInds1D_.dimension_0 () != 0) { // 1-D storage
        const size_t start = rowinfo.offset1D;
        const size_t len = rowinfo.allocSize;
        const std::pair<size_t, size_t> rng (start, start + len);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_gblInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        return Kokkos::subview (row_view_type (this->k_gblInds1D_), rng);
      }
      else if (! this->gblInds2D_[rowinfo.localRow].empty ()) { // 2-D storage
        Teuchos::ArrayView<const GO> rowAv = this->gblInds2D_[rowinfo.localRow] ();
        // FIXME (mfh 26 Nov 2015) This assumes UVM, because it
        // assumes that host code can access device memory through
        // Teuchos::ArrayView.
        return row_view_type (rowAv.getRawPtr (), rowAv.size ());
      }
      else {
        return row_view_type (); // nothing in the row to view
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::ArrayView<const GlobalOrdinal>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalView (const RowInfo rowinfo) const
  {
    Teuchos::ArrayView<const GlobalOrdinal> view;
    if (rowinfo.allocSize > 0) {
      if (k_gblInds1D_.dimension_0 () != 0) {
        auto rng = std::make_pair (rowinfo.offset1D,
                                   rowinfo.offset1D + rowinfo.allocSize);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_gblInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        Kokkos::View<const GlobalOrdinal*, execution_space,
          Kokkos::MemoryUnmanaged> k_gblInds1D_unmanaged = k_gblInds1D_;
        view = Kokkos::Compat::getConstArrayView (Kokkos::subview (k_gblInds1D_unmanaged, rng));
      }
      else if (! gblInds2D_[rowinfo.localRow].empty()) {
        view = gblInds2D_[rowinfo.localRow] ();
      }
    }
    return view;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  LocalOrdinal
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalViewRawConst (const GlobalOrdinal*& gblInds,
                         LocalOrdinal& numEnt,
                         const RowInfo& rowinfo) const
  {
    gblInds = NULL;
    numEnt = 0;

    if (rowinfo.allocSize != 0) {
      if (k_gblInds1D_.dimension_0 () != 0) { // 1-D storage
#ifdef HAVE_TPETRA_DEBUG
        if (rowinfo.offset1D + rowinfo.allocSize >
            static_cast<size_t> (k_gblInds1D_.dimension_0 ())) {
          return static_cast<LocalOrdinal> (-1);
        }
#endif // HAVE_TPETRA_DEBUG
        gblInds = &k_gblInds1D_[rowinfo.offset1D];
        numEnt = rowinfo.allocSize;
      }
      else {
#ifdef HAVE_TPETRA_DEBUG
        if (rowinfo.localRow >= static_cast<size_t> (gblInds2D_.size ())) {
          return static_cast<LocalOrdinal> (-1);
        }
#endif // HAVE_TPETRA_DEBUG
        const auto& curRow = gblInds2D_[rowinfo.localRow];
        if (! curRow.empty ()) {
          gblInds = curRow.getRawPtr ();
          numEnt = curRow.size ();
        }
      }
    }
    return static_cast<LocalOrdinal> (0);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::ArrayView<GlobalOrdinal>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalViewNonConst (const RowInfo rowinfo)
  {
    Teuchos::ArrayView<GlobalOrdinal> view;
    if (rowinfo.allocSize > 0) {
      if (k_gblInds1D_.dimension_0 () != 0) {
        auto rng = std::make_pair (rowinfo.offset1D,
                                   rowinfo.offset1D + rowinfo.allocSize);
        // mfh 23 Nov 2015: Don't just create a subview of
        // k_gblInds1D_ directly, because that first creates a
        // _managed_ subview, then returns an unmanaged version of
        // that.  That touches the reference count, which costs
        // performance in a measurable way.
        Kokkos::View<GlobalOrdinal*, execution_space,
          Kokkos::MemoryUnmanaged> k_gblInds1D_unmanaged = k_gblInds1D_;
        view = Kokkos::Compat::getArrayView (Kokkos::subview (k_gblInds1D_unmanaged, rng));
      }
      else if (! gblInds2D_[rowinfo.localRow].empty()) {
        view = gblInds2D_[rowinfo.localRow] ();
      }
    }
    return view;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  RowInfo
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getRowInfo (const LocalOrdinal myRow) const
  {
#ifdef HAVE_TPETRA_DEBUG
    const char tfecfFuncName[] = "getRowInfo: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::logic_error,
      "Late catch! Graph does not have row info anymore.  "
      "Error should have been caught earlier.  "
      "Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG

    const size_t STINV = Teuchos::OrdinalTraits<size_t>::invalid ();
    RowInfo ret;
    if (! hasRowInfo () || rowMap_.is_null () ||
        ! rowMap_->isNodeLocalElement (myRow)) {
      ret.localRow = STINV;
      ret.allocSize = 0;
      ret.numEntries = 0;
      ret.offset1D = STINV;
      return ret;
    }

    ret.localRow = static_cast<size_t> (myRow);
    if (nodeNumAllocated_ != 0 && nodeNumAllocated_ != STINV) {
      // graph data structures have the info that we need
      //
      // if static graph, offsets tell us the allocation size
      if (getProfileType() == StaticProfile) {
        ret.offset1D  = k_rowPtrs_(myRow);
        ret.allocSize = k_rowPtrs_(myRow+1) - k_rowPtrs_(myRow);
        if (k_numRowEntries_.dimension_0 () == 0) {
          ret.numEntries = ret.allocSize;
        } else {
          ret.numEntries = k_numRowEntries_(myRow);
        }
      }
      else {
        ret.offset1D = STINV;
        if (isLocallyIndexed ()) {
          ret.allocSize = lclInds2D_[myRow].size ();
        }
        else {
          ret.allocSize = gblInds2D_[myRow].size ();
        }
        ret.numEntries = k_numRowEntries_(myRow);
      }
    }
    else if (nodeNumAllocated_ == 0) {
      // have performed allocation, but the graph has no allocation or entries
      ret.allocSize = 0;
      ret.numEntries = 0;
      ret.offset1D = STINV;
    }
    else if (! indicesAreAllocated ()) {
      // haven't performed allocation yet; probably won't hit this code
      //
      // FIXME (mfh 07 Aug 2014) We want graph's constructors to
      // allocate, rather than doing lazy allocation at first insert.
      // This will make k_numAllocPerRow_ obsolete.
      const bool useNumAllocPerRow = (k_numAllocPerRow_.dimension_0 () != 0);
      if (useNumAllocPerRow) {
        ret.allocSize = k_numAllocPerRow_(myRow); // this is a host View
      } else {
        ret.allocSize = numAllocForAllRows_;
      }
      ret.numEntries = 0;
      ret.offset1D = STINV;
    }
    else {
      // don't know how we ended up here...
      TEUCHOS_TEST_FOR_EXCEPT(true);
    }
    return ret;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  RowInfo
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getRowInfoFromGlobalRowIndex (const GlobalOrdinal gblRow) const
  {
    const size_t STINV = Teuchos::OrdinalTraits<size_t>::invalid ();
    RowInfo ret;
    if (! this->hasRowInfo () || this->rowMap_.is_null ()) {
      ret.localRow = STINV;
      ret.allocSize = 0;
      ret.numEntries = 0;
      ret.offset1D = STINV;
      return ret;
    }
    const LocalOrdinal myRow = this->rowMap_->getLocalElement (gblRow);
    if (myRow == Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
      ret.localRow = STINV;
      ret.allocSize = 0;
      ret.numEntries = 0;
      ret.offset1D = STINV;
      return ret;
    }

    ret.localRow = static_cast<size_t> (myRow);
    if (nodeNumAllocated_ != 0 && nodeNumAllocated_ != STINV) {
      // graph data structures have the info that we need
      //
      // if static graph, offsets tell us the allocation size
      if (getProfileType() == StaticProfile) {
        ret.offset1D  = k_rowPtrs_(myRow);
        ret.allocSize = k_rowPtrs_(myRow+1) - k_rowPtrs_(myRow);
        if (k_numRowEntries_.dimension_0 () == 0) {
          ret.numEntries = ret.allocSize;
        } else {
          ret.numEntries = k_numRowEntries_(myRow);
        }
      }
      else {
        ret.offset1D = STINV;
        if (isLocallyIndexed ()) {
          ret.allocSize = lclInds2D_[myRow].size ();
        }
        else {
          ret.allocSize = gblInds2D_[myRow].size ();
        }
        ret.numEntries = k_numRowEntries_(myRow);
      }
    }
    else if (nodeNumAllocated_ == 0) {
      // have performed allocation, but the graph has no allocation or entries
      ret.allocSize = 0;
      ret.numEntries = 0;
      ret.offset1D = STINV;
    }
    else if (! indicesAreAllocated ()) {
      // haven't performed allocation yet; probably won't hit this code
      //
      // FIXME (mfh 07 Aug 2014) We want graph's constructors to
      // allocate, rather than doing lazy allocation at first insert.
      // This will make k_numAllocPerRow_ obsolete.
      const bool useNumAllocPerRow = (k_numAllocPerRow_.dimension_0 () != 0);
      if (useNumAllocPerRow) {
        ret.allocSize = k_numAllocPerRow_(myRow); // this is a host View
      } else {
        ret.allocSize = numAllocForAllRows_;
      }
      ret.numEntries = 0;
      ret.offset1D = STINV;
    }
    else {
      // don't know how we ended up here...
      TEUCHOS_TEST_FOR_EXCEPT(true);
    }
    return ret;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  staticAssertions () const
  {
    using Teuchos::OrdinalTraits;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    typedef global_size_t GST;

    // Assumption: sizeof(GlobalOrdinal) >= sizeof(LocalOrdinal):
    //     This is so that we can store local indices in the memory
    //     formerly occupied by global indices.
    static_assert (sizeof (GlobalOrdinal) >= sizeof (LocalOrdinal),
                   "Tpetra::CrsGraph: sizeof(GlobalOrdinal) must be >= sizeof(LocalOrdinal).");
    // Assumption: max(size_t) >= max(LocalOrdinal)
    //     This is so that we can represent any LocalOrdinal as a size_t.
    static_assert (sizeof (size_t) >= sizeof (LocalOrdinal),
                   "Tpetra::CrsGraph: sizeof(size_t) must be >= sizeof(LocalOrdinal).");
    static_assert (sizeof(GST) >= sizeof(size_t),
                   "Tpetra::CrsGraph: sizeof(Tpetra::global_size_t) must be >= sizeof(size_t).");

    // FIXME (mfh 30 Sep 2015) We're not using
    // Teuchos::CompileTimeAssert any more.  Can we do these checks
    // with static_assert?

    // can't call max() with CompileTimeAssert, because it isn't a
    // constant expression; will need to make this a runtime check
    const char msg[] = "Tpetra::CrsGraph: Object cannot be created with the "
      "given template arguments: size assumptions are not valid.";
    TEUCHOS_TEST_FOR_EXCEPTION(
      static_cast<size_t> (Teuchos::OrdinalTraits<LO>::max ()) > Teuchos::OrdinalTraits<size_t>::max (),
      std::runtime_error, msg);
    TEUCHOS_TEST_FOR_EXCEPTION(
      static_cast<GST> (Teuchos::OrdinalTraits<LO>::max ()) > static_cast<GST> (Teuchos::OrdinalTraits<GO>::max ()),
      std::runtime_error, msg);
    TEUCHOS_TEST_FOR_EXCEPTION(
      static_cast<size_t> (Teuchos::OrdinalTraits<GO>::max ()) > Teuchos::OrdinalTraits<GST>::max(),
      std::runtime_error, msg);
    TEUCHOS_TEST_FOR_EXCEPTION(
      Teuchos::OrdinalTraits<size_t>::max () > Teuchos::OrdinalTraits<GST>::max (),
      std::runtime_error, msg);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertIndices (const RowInfo& rowinfo,
                 const SLocalGlobalViews &newInds,
                 const ELocalGlobal lg,
                 const ELocalGlobal I)
  {
    using Teuchos::ArrayView;
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      lg != GlobalIndices && lg != LocalIndices, std::invalid_argument,
      "Tpetra::CrsGraph::insertIndices: lg must be either GlobalIndices or "
      "LocalIndices.");
#endif // HAVE_TPETRA_DEBUG
    size_t numNewInds = 0;
    if (lg == GlobalIndices) { // input indices are global
      ArrayView<const GlobalOrdinal> new_ginds = newInds.ginds;
      numNewInds = new_ginds.size();
      if (I == GlobalIndices) { // store global indices
        ArrayView<GlobalOrdinal> gind_view = getGlobalViewNonConst(rowinfo);
        std::copy(new_ginds.begin(), new_ginds.end(), gind_view.begin()+rowinfo.numEntries);
      }
      else if (I == LocalIndices) { // store local indices
        ArrayView<LocalOrdinal> lind_view = getLocalViewNonConst(rowinfo);
        typename ArrayView<const GlobalOrdinal>::iterator         in = new_ginds.begin();
        const typename ArrayView<const GlobalOrdinal>::iterator stop = new_ginds.end();
        typename ArrayView<LocalOrdinal>::iterator out = lind_view.begin()+rowinfo.numEntries;
        while (in != stop) {
          *out++ = colMap_->getLocalElement (*in++);
        }
      }
    }
    else if (lg == LocalIndices) { // input indices are local
      ArrayView<const LocalOrdinal> new_linds = newInds.linds;
      numNewInds = new_linds.size();
      if (I == LocalIndices) { // store local indices
        ArrayView<LocalOrdinal> lind_view = getLocalViewNonConst(rowinfo);
        std::copy(new_linds.begin(), new_linds.end(), lind_view.begin()+rowinfo.numEntries);
      }
      else if (I == GlobalIndices) {
        TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Tpetra::CrsGraph::"
          "insertIndices: the case where the input indices are local and the "
          "indices to write are global (lg=LocalIndices, I=GlobalIndices) is "
          "not implemented, because it does not make sense." << std::endl <<
          "If you have correct local column indices, that means the graph has "
          "a column Map.  In that case, you should be storing local indices.");
      }
    }

    k_numRowEntries_(rowinfo.localRow) += numNewInds;
    nodeNumEntries_ += numNewInds;
    setLocallyModified ();
    return numNewInds;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertGlobalIndicesImpl (const LocalOrdinal myRow,
                           const Teuchos::ArrayView<const GlobalOrdinal>& indices)
  {
    using Kokkos::subview;
    typedef Kokkos::pair<size_t, size_t> range_type;
    const char tfecfFuncName[] = "insertGlobalIndicesImpl: ";

    RowInfo rowInfo = getRowInfo(myRow);
    size_t numNewInds = indices.size();
    size_t newNumEntries = rowInfo.numEntries + numNewInds;

    if (newNumEntries > rowInfo.allocSize) {
      if (getProfileType () == StaticProfile) {

        // Count how many new indices are just duplicates of the old
        // ones.  If enough are duplicates, then we're safe.
        //
        // TODO (09 Sep 2016) CrsGraph never supported this use case
        // before.  Thus, we're justified in not optimizing it.  We
        // could use binary search if the graph's current entries are
        // sorted, for example, but we just use linear search for now.

        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (rowInfo.numEntries > rowInfo.allocSize, std::logic_error,
           "For local row " << myRow << ", rowInfo.numEntries = "
           << rowInfo.numEntries << " > rowInfo.allocSize = "
           << rowInfo.allocSize
           << ".  Please report this bug to the Tpetra developers.");

        size_t dupCount = 0;
        if (k_gblInds1D_.dimension_0 () != 0) {
          const size_t curOffset = rowInfo.offset1D;
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (k_gblInds1D_.dimension_0 ()) < curOffset,
             std::logic_error, "k_gblInds1D_.dimension_0() = " <<
             k_gblInds1D_.dimension_0 () << " < offset1D = " << curOffset
             << ".  Please report this bug to the Tpetra developers.");
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (k_gblInds1D_.dimension_0 ()) <
             curOffset + rowInfo.numEntries,
             std::logic_error, "k_gblInds1D_.dimension_0() = " <<
             k_gblInds1D_.dimension_0 () << " < offset1D (= " << curOffset <<
             ") + rowInfo.numEntries (= " << rowInfo.numEntries << ").  Please "
             "report this bug to the Tpetra developers.");
          const Kokkos::pair<size_t, size_t>
            range (curOffset, curOffset + rowInfo.numEntries);

          auto gblIndsCur = subview (k_gblInds1D_, range);
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (gblIndsCur.dimension_0 ()) != rowInfo.numEntries,
             std::logic_error, "gblIndsCur.dimension_0() = " <<
             gblIndsCur.dimension_0 () << " != rowInfo.numEntries = " <<
             rowInfo.numEntries << ".  Please report this bug to the Tpetra "
             "developers.");

          const size_t numInput = static_cast<size_t> (indices.size ());
          for (size_t k_new = 0; k_new < numInput; ++k_new) {
            const GlobalOrdinal gblIndToInsert = indices[k_new];
            for (size_t k_old = 0; k_old < rowInfo.numEntries; ++k_old) {
              if (gblIndsCur[k_old] == gblIndToInsert) {
                // Input could itself have duplicates.  Input is
                // const, so we can't remove duplicates.  That's OK
                // here, though, because dupCount just refers to the
                // number of input entries that actually need to be
                // inserted.
                ++dupCount;
              }
            }
          }
        }
        else {
          Teuchos::ArrayView<GlobalOrdinal> gblInds = (gblInds2D_[myRow]) ();
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (rowInfo.allocSize != static_cast<size_t> (gblInds.size ()),
             std::logic_error, "rowInfo.allocSize = " << rowInfo.allocSize
             << " != gblInds.size() = " << gblInds.size ()
             << ".  Please report this bug to the Tpetra developers.");
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (rowInfo.numEntries > static_cast<size_t> (gblInds.size ()),
             std::logic_error, "rowInfo.numEntries = " << rowInfo.numEntries
             << " > gblInds.size() = " << gblInds.size ()
             << ".  Please report this bug to the Tpetra developers.");
          auto gblIndsCur = gblInds (0, rowInfo.numEntries);

          const size_t numInput = static_cast<size_t> (indices.size ());
          for (size_t k_new = 0; k_new < numInput; ++k_new) {
            const GlobalOrdinal gblIndToInsert = indices[k_new];
            for (size_t k_old = 0; k_old < rowInfo.numEntries; ++k_old) {
              if (gblIndsCur[k_old] == gblIndToInsert) {
                // Input could itself have duplicates.  Input is
                // const, so we can't remove duplicates.  That's OK
                // here, though, because dupCount just refers to the
                // number of input entries that actually need to be
                // inserted.
                ++dupCount;
              }
            }
          }
        }

        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (static_cast<size_t> (indices.size ()) < dupCount, std::logic_error,
           "indices.size() = " << indices.size () << " < dupCount = " <<
           dupCount << ".  Please report this bug to the Tpetra developers.");
        const size_t numNewToInsert =
          static_cast<size_t> (indices.size ()) - dupCount;

        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (rowInfo.numEntries + numNewToInsert > rowInfo.allocSize,
           std::runtime_error, "For local row " << myRow << " on Process " <<
           this->getComm ()->getRank () << ", even after excluding " << dupCount
           << " duplicate(s) in input, the new number of entries " <<
           (rowInfo.numEntries + numNewToInsert) << " still exceeds this row's "
           "static allocation size " << rowInfo.allocSize << ".  You must "
           "either fix the upper bound on the number of entries in this row, "
           "or switch from StaticProfile to DynamicProfile.");

        if (k_gblInds1D_.dimension_0 () != 0) {
          const size_t curOffset = rowInfo.offset1D;
          auto gblIndsCur =
            subview (k_gblInds1D_, range_type (curOffset,
                                               curOffset + rowInfo.numEntries));
          auto gblIndsNew =
            subview (k_gblInds1D_, range_type (curOffset + rowInfo.numEntries,
                                               curOffset + rowInfo.allocSize));

          size_t curPos = 0;
          for (size_t k_new = 0; k_new < numNewInds; ++k_new) {
            const GlobalOrdinal gblIndToInsert = indices[k_new];

            bool isAlreadyInOld = false;
            for (size_t k_old = 0; k_old < rowInfo.numEntries; ++k_old) {
              if (gblIndsCur[k_old] == gblIndToInsert) {
                isAlreadyInOld = true;
                break;
              }
            }
            if (! isAlreadyInOld) {
              TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
                (curPos >= numNewToInsert, std::logic_error, "curPos = " <<
                 curPos << " >= numNewToInsert = " << numNewToInsert << ".  "
                 "Please report this bug to the Tpetra developers.");
              gblIndsNew[curPos] = gblIndToInsert;
              ++curPos;
            }
          } // for each input column index
        }
        else {
          Teuchos::ArrayView<GlobalOrdinal> gblInds = (gblInds2D_[myRow]) ();
          // Teuchos::ArrayView::operator() takes (offset, size).
          auto gblIndsCur = gblInds (0, rowInfo.numEntries);
          auto gblIndsNew = gblInds (rowInfo.numEntries,
                                     rowInfo.allocSize - rowInfo.numEntries);

          size_t curPos = 0;
          for (size_t k_new = 0; k_new < numNewInds; ++k_new) {
            const GlobalOrdinal gblIndToInsert = indices[k_new];

            bool isAlreadyInOld = false;
            for (size_t k_old = 0; k_old < rowInfo.numEntries; ++k_old) {
              if (gblIndsCur[k_old] == gblIndToInsert) {
                isAlreadyInOld = true;
                break;
              }
            }
            if (! isAlreadyInOld) {
              TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
                (curPos >= numNewToInsert, std::logic_error, "curPos = " <<
                 curPos << " >= numNewToInsert = " << numNewToInsert << ".  "
                 "Please report this bug to the Tpetra developers.");
              gblIndsNew[curPos] = gblIndToInsert;
              ++curPos;
            }
          } // for each input column index
        }

        k_numRowEntries_(myRow) = rowInfo.numEntries + numNewToInsert;
        nodeNumEntries_ += numNewToInsert;
        setLocallyModified ();

#ifdef HAVE_TPETRA_DEBUG
        newNumEntries = rowInfo.numEntries + numNewToInsert;
        const size_t chkNewNumEntries = getNumEntriesInLocalRow (myRow);
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (chkNewNumEntries != newNumEntries, std::logic_error,
           "After inserting new entries, getNumEntriesInLocalRow(" << myRow <<
           ") = " << chkNewNumEntries << " != newNumEntries = " << newNumEntries
           << ".  Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG

        return; // all done!
      }
      else {
        // update allocation, doubling size to reduce # reallocations
        size_t newAllocSize = 2*rowInfo.allocSize;
        if (newAllocSize < newNumEntries) {
          newAllocSize = newNumEntries;
        }
        gblInds2D_[myRow].resize(newAllocSize);
        nodeNumAllocated_ += (newAllocSize - rowInfo.allocSize);
      }
    }

    // Copy new indices at end of global index array
    if (k_gblInds1D_.dimension_0 () != 0) {
      const size_t numIndsToCopy = static_cast<size_t> (indices.size ());
      const size_t offset = rowInfo.offset1D + rowInfo.numEntries;
      for (size_t k = 0; k < numIndsToCopy; ++k) {
        k_gblInds1D_[offset + k] = indices[k];
      }
    }
    else {
      std::copy(indices.begin(), indices.end(),
                gblInds2D_[myRow].begin()+rowInfo.numEntries);
    }

    k_numRowEntries_(myRow) += numNewInds;
    nodeNumEntries_ += numNewInds;
    setLocallyModified ();

#ifdef HAVE_TPETRA_DEBUG
    {
      const size_t chkNewNumEntries = getNumEntriesInLocalRow (myRow);
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        chkNewNumEntries != newNumEntries, std::logic_error,
        ": Internal logic error. Please contact Tpetra team.");
    }
#endif
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertLocalIndicesImpl (const LocalOrdinal myRow,
                          const Teuchos::ArrayView<const LocalOrdinal>& indices)
  {
    using Kokkos::MemoryUnmanaged;
    using Kokkos::subview;
    using Kokkos::View;
    typedef LocalOrdinal LO;
    const char* tfecfFuncName ("insertLocallIndicesImpl");

    const RowInfo rowInfo = this->getRowInfo(myRow);
    const size_t numNewInds = indices.size();
    const size_t newNumEntries = rowInfo.numEntries + numNewInds;
    if (newNumEntries > rowInfo.allocSize) {
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        getProfileType() == StaticProfile, std::runtime_error,
        ": new indices exceed statically allocated graph structure.");

      // update allocation, doubling size to reduce number of reallocations
      size_t newAllocSize = 2*rowInfo.allocSize;
      if (newAllocSize < newNumEntries)
        newAllocSize = newNumEntries;
      lclInds2D_[myRow].resize(newAllocSize);
      nodeNumAllocated_ += (newAllocSize - rowInfo.allocSize);
    }

    // Store the new indices at the end of row myRow.
    if (k_lclInds1D_.dimension_0 () != 0) {
      typedef View<const LO*, execution_space, MemoryUnmanaged> input_view_type;
      typedef View<LO*, execution_space, MemoryUnmanaged> row_view_type;

      input_view_type inputInds (indices.getRawPtr (), indices.size ());
      const size_t start = rowInfo.offset1D + rowInfo.numEntries; // end of row
      const std::pair<size_t, size_t> rng (start, start + newNumEntries);
      // mfh 23 Nov 2015: Don't just create a subview of k_lclInds1D_
      // directly, because that first creates a _managed_ subview,
      // then returns an unmanaged version of that.  That touches the
      // reference count, which costs performance in a measurable way.
      row_view_type myInds = subview (row_view_type (k_lclInds1D_), rng);
      Kokkos::deep_copy (myInds, inputInds);
    }
    else {
      std::copy (indices.begin (), indices.end (),
                 lclInds2D_[myRow].begin () + rowInfo.numEntries);
    }

    k_numRowEntries_(myRow) += numNewInds;
    nodeNumEntries_ += numNewInds;
    setLocallyModified ();
#ifdef HAVE_TPETRA_DEBUG
    {
      const size_t chkNewNumEntries = getNumEntriesInLocalRow (myRow);
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        chkNewNumEntries != newNumEntries, std::logic_error,
        ": Internal logic error. Please contact Tpetra team.");
    }
#endif
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  sortRowIndices (const RowInfo rowinfo)
  {
    if (rowinfo.numEntries > 0) {
      Teuchos::ArrayView<LocalOrdinal> inds_view =
        this->getLocalViewNonConst (rowinfo);
      std::sort (inds_view.begin (), inds_view.begin () + rowinfo.numEntries);
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  mergeRowIndices (RowInfo rowinfo)
  {
    using Teuchos::ArrayView;
    const char tfecfFuncName[] = "mergeRowIndices: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isStorageOptimized (), std::logic_error, "The graph is already storage "
      "optimized, so we shouldn't be merging any indices.  "
      "Please report this bug to the Tpetra developers.");

    ArrayView<LocalOrdinal> inds_view = this->getLocalViewNonConst (rowinfo);
    typename ArrayView<LocalOrdinal>::iterator beg, end, newend;
    beg = inds_view.begin();
    end = inds_view.begin() + rowinfo.numEntries;
    newend = std::unique(beg,end);
    const size_t mergedEntries = newend - beg;
#ifdef HAVE_TPETRA_DEBUG
    // merge should not have eliminated any entries; if so, the
    // assignment below will destroy the packed structure
    TEUCHOS_TEST_FOR_EXCEPT( isStorageOptimized () && mergedEntries != rowinfo.numEntries );
#endif // HAVE_TPETRA_DEBUG

    k_numRowEntries_(rowinfo.localRow) = mergedEntries;
    nodeNumEntries_ -= (rowinfo.numEntries - mergedEntries);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  setDomainRangeMaps (const Teuchos::RCP<const map_type>& domainMap,
                      const Teuchos::RCP<const map_type>& rangeMap)
  {
    // simple pointer comparison for equality
    if (domainMap_ != domainMap) {
      domainMap_ = domainMap;
      importer_ = Teuchos::null;
    }
    if (rangeMap_ != rangeMap) {
      rangeMap_  = rangeMap;
      exporter_ = Teuchos::null;
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  clearGlobalConstants ()
  {
    globalNumEntries_       = Teuchos::OrdinalTraits<global_size_t>::invalid ();
    globalNumDiags_         = Teuchos::OrdinalTraits<global_size_t>::invalid ();
    globalMaxNumRowEntries_ = Teuchos::OrdinalTraits<global_size_t>::invalid ();
    haveGlobalConstants_    = false;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  checkInternalState () const
  {
#ifdef HAVE_TPETRA_DEBUG
    const global_size_t GSTI = Teuchos::OrdinalTraits<global_size_t>::invalid ();
    const size_t         STI = Teuchos::OrdinalTraits<size_t>::invalid ();
    const char err[] = "Tpetra::CrsGraph::checkInternalState: Likely internal "
      "logic error.  Please contact Tpetra team.";
    // check the internal state of this data structure
    // this is called by numerous state-changing methods, in a debug build, to ensure that the object
    // always remains in a valid state
    // the graph should have been allocated with a row map
    TEUCHOS_TEST_FOR_EXCEPTION( rowMap_ == Teuchos::null,                     std::logic_error, err );
    // am either complete or active
    TEUCHOS_TEST_FOR_EXCEPTION( isFillActive() == isFillComplete(),  std::logic_error, err );
    // if the graph has been fill completed, then all maps should be present
    TEUCHOS_TEST_FOR_EXCEPTION( isFillComplete() == true && (colMap_ == Teuchos::null || rangeMap_ == Teuchos::null || domainMap_ == Teuchos::null), std::logic_error, err );
    // if storage has been optimized, then indices should have been allocated (even if trivially so)
    TEUCHOS_TEST_FOR_EXCEPTION( isStorageOptimized() == true && indicesAreAllocated() == false, std::logic_error, err );
    // if storage has been optimized, then number of allocated is now the number of entries
    TEUCHOS_TEST_FOR_EXCEPTION( isStorageOptimized() == true && getNodeAllocationSize() != getNodeNumEntries(), std::logic_error, err );
    // if graph doesn't have the global constants, then they should all be marked as invalid
    TEUCHOS_TEST_FOR_EXCEPTION( haveGlobalConstants_ == false && ( globalNumEntries_ != GSTI || globalNumDiags_ != GSTI || globalMaxNumRowEntries_ != GSTI ), std::logic_error, err );
    // if the graph has global cosntants, then they should be valid.
    TEUCHOS_TEST_FOR_EXCEPTION( haveGlobalConstants_ == true && ( globalNumEntries_ == GSTI || globalNumDiags_ == GSTI || globalMaxNumRowEntries_ == GSTI ), std::logic_error, err );
    TEUCHOS_TEST_FOR_EXCEPTION( haveGlobalConstants_ == true && ( globalNumEntries_ < nodeNumEntries_ || globalNumDiags_ < nodeNumDiags_ || globalMaxNumRowEntries_ < nodeMaxNumRowEntries_ ),
                        std::logic_error, err );
    // if indices are allocated, then the allocation specifications should have been released
    TEUCHOS_TEST_FOR_EXCEPTION(
      indicesAreAllocated () && (numAllocForAllRows_ != 0 ||
                                 k_numAllocPerRow_.dimension_0 () != 0),
      std::logic_error, err );
    // if indices are not allocated, then information dictating allocation quantities should be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      ! indicesAreAllocated () && (nodeNumAllocated_ != STI ||
                                   nodeNumEntries_ != 0),
      std::logic_error, err );
    // if storage is optimized, then profile should be static
    TEUCHOS_TEST_FOR_EXCEPTION( isStorageOptimized() && pftype_ != StaticProfile,                                                               std::logic_error, err );

    // If k_rowPtrs_ exists (has nonzero size), it must have N+1 rows,
    // and k_rowPtrs_(N) must equal k_gblInds1D_.dimension_0() (if
    // globally indexed) or k_lclInds1D_.dimension_0() (if locally
    // indexed).

    TEUCHOS_TEST_FOR_EXCEPTION(
      isGloballyIndexed () && k_rowPtrs_.dimension_0 () != 0 &&
      (static_cast<size_t> (k_rowPtrs_.dimension_0 ()) != getNodeNumRows () + 1 ||
       k_rowPtrs_(getNodeNumRows ()) != static_cast<size_t> (k_gblInds1D_.dimension_0 ())),
      std::logic_error, err );

    TEUCHOS_TEST_FOR_EXCEPTION(
      isLocallyIndexed () && k_rowPtrs_.dimension_0 () != 0 &&
      (static_cast<size_t> (k_rowPtrs_.dimension_0 ()) != getNodeNumRows () + 1 ||
       k_rowPtrs_(getNodeNumRows ()) != static_cast<size_t> (k_lclInds1D_.dimension_0 ())),
      std::logic_error, err );

    // If profile is dynamic and indices are allocated, then 2-D
    // allocations of column index storage (either local or global)
    // must be present.
    TEUCHOS_TEST_FOR_EXCEPTION(
      pftype_ == DynamicProfile &&
      indicesAreAllocated () &&
      getNodeNumRows () > 0 &&
      lclInds2D_.is_null () && gblInds2D_.is_null (),
      std::logic_error, err );

    // If profile is dynamic and the calling process owns nonzero
    // rows, then k_numRowEntries_ and 2-D storage of column indices
    // (whether local or global) must be present.
    TEUCHOS_TEST_FOR_EXCEPTION(
      pftype_ == DynamicProfile &&
      indicesAreAllocated () &&
      getNodeNumRows () > 0 &&
      (k_numRowEntries_.dimension_0 () == 0 ||
       (lclInds2D_.is_null () && gblInds2D_.is_null ())),
      std::logic_error, err );

    // if profile is dynamic, then 1D allocations should not be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      pftype_ == DynamicProfile &&
      (k_lclInds1D_.dimension_0 () != 0 || k_gblInds1D_.dimension_0 () != 0),
      std::logic_error, err );
    // if profile is dynamic, then row offsets should not be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      pftype_ == DynamicProfile && k_rowPtrs_.dimension_0 () != 0,
      std::logic_error, err );
    // if profile is static and we have allocated non-trivially, then
    // 1D allocations should be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      pftype_ == StaticProfile && indicesAreAllocated () &&
      getNodeAllocationSize () > 0 && k_lclInds1D_.dimension_0 () == 0 &&
      k_gblInds1D_.dimension_0 () == 0,
      std::logic_error, err);
    // if profile is static, then 2D allocations should not be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      pftype_ == StaticProfile && (lclInds2D_ != Teuchos::null || gblInds2D_ != Teuchos::null),
      std::logic_error, err );

    // if indices are not allocated, then none of the buffers should be.
    TEUCHOS_TEST_FOR_EXCEPTION(
      ! indicesAreAllocated () &&
      ((k_rowPtrs_.dimension_0 () != 0 || k_numRowEntries_.dimension_0 () != 0) ||
       k_lclInds1D_.dimension_0 () != 0 || lclInds2D_ != Teuchos::null ||
       k_gblInds1D_.dimension_0 () != 0 || gblInds2D_ != Teuchos::null),
      std::logic_error, err );

    // indices may be local or global only if they are allocated
    // (numAllocated is redundant; could simply be indicesAreLocal_ ||
    // indicesAreGlobal_)
    TEUCHOS_TEST_FOR_EXCEPTION( (indicesAreLocal_ || indicesAreGlobal_) && ! indicesAreAllocated_, std::logic_error, err );
    // indices may be local or global, but not both
    TEUCHOS_TEST_FOR_EXCEPTION( indicesAreLocal_ == true && indicesAreGlobal_ == true,                                                  std::logic_error, err );
    // if indices are local, then global allocations should not be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      indicesAreLocal_ && (k_gblInds1D_.dimension_0 () != 0 || gblInds2D_ != Teuchos::null),
      std::logic_error, err );
    // if indices are global, then local allocations should not be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      indicesAreGlobal_ && (k_lclInds1D_.dimension_0 () != 0 || lclInds2D_ != Teuchos::null),
      std::logic_error, err );
    // if indices are local, then local allocations should be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      indicesAreLocal_ && getNodeAllocationSize () > 0 &&
      k_lclInds1D_.dimension_0 () == 0 && getNodeNumRows () > 0 &&
      lclInds2D_.is_null (),
      std::logic_error, err);
    // if indices are global, then global allocations should be present
    TEUCHOS_TEST_FOR_EXCEPTION(
      indicesAreGlobal_ && getNodeAllocationSize () > 0 &&
      k_gblInds1D_.dimension_0 () == 0 && getNodeNumRows () > 0 &&
      gblInds2D_.is_null (),
      std::logic_error, err);
    // if indices are allocated, then we should have recorded how many were allocated
    TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == true  && nodeNumAllocated_ == STI,                                       std::logic_error, err );
    // if indices are not allocated, then the allocation size should be marked invalid
    TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == false && nodeNumAllocated_ != STI,                                       std::logic_error, err );
    // check the actual allocations
    if (indicesAreAllocated()) {
      size_t actualNumAllocated = 0;
      if (pftype_ == DynamicProfile) {
        if (isGloballyIndexed() && gblInds2D_ != Teuchos::null) {
          for (size_t r = 0; r < getNodeNumRows(); ++r) {
            actualNumAllocated += gblInds2D_[r].size();
          }
        }
        else if (isLocallyIndexed() && lclInds2D_ != Teuchos::null) {
          for (size_t r = 0; r < getNodeNumRows(); ++r) {
            actualNumAllocated += lclInds2D_[r].size();
          }
        }
        TEUCHOS_TEST_FOR_EXCEPTION(actualNumAllocated != nodeNumAllocated_, std::logic_error, err );
      }
      else if (k_rowPtrs_.dimension_0 () != 0) { // pftype_ == StaticProfile
        TEUCHOS_TEST_FOR_EXCEPTION(
          static_cast<size_t> (k_rowPtrs_.dimension_0 ()) != getNodeNumRows () + 1,
          std::logic_error, err);

        actualNumAllocated = k_rowPtrs_(getNodeNumRows ());
        TEUCHOS_TEST_FOR_EXCEPTION(
          isLocallyIndexed () &&
          static_cast<size_t> (k_lclInds1D_.dimension_0 ()) != actualNumAllocated,
          std::logic_error, err );
        TEUCHOS_TEST_FOR_EXCEPTION(
          isGloballyIndexed () &&
          static_cast<size_t> (k_gblInds1D_.dimension_0 ()) != actualNumAllocated,
          std::logic_error, err );
        TEUCHOS_TEST_FOR_EXCEPTION(actualNumAllocated != nodeNumAllocated_, std::logic_error, err );
      }
    }
#endif // HAVE_TPETRA_DEBUG
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNumEntriesInGlobalRow (GlobalOrdinal globalRow) const
  {
    using Teuchos::OrdinalTraits;
    const LocalOrdinal lrow = rowMap_->getLocalElement (globalRow);
    if (hasRowInfo () && lrow != OrdinalTraits<LocalOrdinal>::invalid ()) {
      const RowInfo rowinfo = this->getRowInfo (lrow);
      return rowinfo.numEntries;
    } else {
      return OrdinalTraits<size_t>::invalid ();
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNumEntriesInLocalRow (LocalOrdinal localRow) const
  {
    if (hasRowInfo () && rowMap_->isNodeLocalElement (localRow)) {
      const RowInfo rowinfo = this->getRowInfo (localRow);
      return rowinfo.numEntries;
    } else {
      return Teuchos::OrdinalTraits<size_t>::invalid ();
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNumAllocatedEntriesInGlobalRow (GlobalOrdinal globalRow) const
  {
    const LocalOrdinal lrow = rowMap_->getLocalElement (globalRow);
    if (hasRowInfo () && lrow != Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
      const RowInfo rowinfo = this->getRowInfo (lrow);
      return rowinfo.allocSize;
    } else {
      return Teuchos::OrdinalTraits<size_t>::invalid ();
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  size_t
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNumAllocatedEntriesInLocalRow (LocalOrdinal localRow) const
  {
    if (hasRowInfo () && rowMap_->isNodeLocalElement (localRow)) {
      const RowInfo rowinfo = this->getRowInfo (localRow);
      return rowinfo.allocSize;
    } else {
      return Teuchos::OrdinalTraits<size_t>::invalid();
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::ArrayRCP<const size_t>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodeRowPtrs () const
  {
    using Kokkos::ViewAllocateWithoutInitializing;
    using Kokkos::create_mirror_view;
    using Teuchos::ArrayRCP;
    typedef typename local_graph_type::row_map_type row_map_type;
    typedef typename row_map_type::non_const_value_type row_offset_type;
#ifdef HAVE_TPETRA_DEBUG
    const char prefix[] = "Tpetra::CrsGraph::getNodeRowPtrs: ";
    const char suffix[] = "  Please report this bug to the Tpetra developers.";
#endif // HAVE_TPETRA_DEBUG
    const size_t size = k_rowPtrs_.dimension_0 ();
    const bool same = Kokkos::Impl::is_same<size_t, row_offset_type>::value;

    if (size == 0) {
      return ArrayRCP<const size_t> ();
    }

    ArrayRCP<const row_offset_type> ptr_rot;
    ArrayRCP<const size_t> ptr_st;
    if (same) { // size_t == row_offset_type
      // NOTE (mfh 22 Mar 2015) In a debug build of Kokkos, the result
      // of create_mirror_view might actually be a new allocation.
      // This helps with debugging when there are two memory spaces.
      typename row_map_type::HostMirror ptr_h = create_mirror_view (k_rowPtrs_);
      Kokkos::deep_copy (ptr_h, k_rowPtrs_);
#ifdef HAVE_TPETRA_DEBUG
      TEUCHOS_TEST_FOR_EXCEPTION(
        ptr_h.dimension_0 () != k_rowPtrs_.dimension_0 (), std::logic_error,
        prefix << "size_t == row_offset_type, but ptr_h.dimension_0() = "
        << ptr_h.dimension_0 () << " != k_rowPtrs_.dimension_0() = "
        << k_rowPtrs_.dimension_0 () << ".");
      TEUCHOS_TEST_FOR_EXCEPTION(
        same && size != 0 && k_rowPtrs_.ptr_on_device () == NULL, std::logic_error,
        prefix << "size_t == row_offset_type and k_rowPtrs_.dimension_0() = "
        << size << " != 0, but k_rowPtrs_.ptr_on_device() == NULL." << suffix);
      TEUCHOS_TEST_FOR_EXCEPTION(
        same && size != 0 && ptr_h.ptr_on_device () == NULL, std::logic_error,
        prefix << "size_t == row_offset_type and k_rowPtrs_.dimension_0() = "
        << size << " != 0, but create_mirror_view(k_rowPtrs_).ptr_on_device() "
        "== NULL." << suffix);
#endif // HAVE_TPETRA_DEBUG
      ptr_rot = Kokkos::Compat::persistingView (ptr_h);
    }
    else { // size_t != row_offset_type
      typedef Kokkos::View<size_t*, device_type> ret_view_type;
      ret_view_type ptr_d (ViewAllocateWithoutInitializing ("ptr"), size);
      ::Tpetra::Details::copyOffsets (ptr_d, k_rowPtrs_);
      typename ret_view_type::HostMirror ptr_h = create_mirror_view (ptr_d);
      Kokkos::deep_copy (ptr_h, ptr_d);
      ptr_st = Kokkos::Compat::persistingView (ptr_h);
    }
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      same && size != 0 && ptr_rot.is_null (), std::logic_error,
      prefix << "size_t == row_offset_type and size = " << size
      << " != 0, but ptr_rot is null." << suffix);
    TEUCHOS_TEST_FOR_EXCEPTION(
      ! same && size != 0 && ptr_st.is_null (), std::logic_error,
      prefix << "size_t != row_offset_type and size = " << size
      << " != 0, but ptr_st is null." << suffix);
#endif // HAVE_TPETRA_DEBUG

    // If size_t == row_offset_type, return a persisting host view of
    // k_rowPtrs_.  Otherwise, return a size_t host copy of k_rowPtrs_.
#ifdef HAVE_TPETRA_DEBUG
    ArrayRCP<const size_t> retval =
      Kokkos::Impl::if_c<same,
        ArrayRCP<const row_offset_type>,
        ArrayRCP<const size_t> >::select (ptr_rot, ptr_st);
    TEUCHOS_TEST_FOR_EXCEPTION(
      size != 0 && retval.is_null (), std::logic_error,
      prefix << "size = " << size << " != 0, but retval is null." << suffix);
    return retval;
#else
    return Kokkos::Impl::if_c<same,
      ArrayRCP<const row_offset_type>,
      ArrayRCP<const size_t> >::select (ptr_rot, ptr_st);
#endif // HAVE_TPETRA_DEBUG
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  Teuchos::ArrayRCP<const LocalOrdinal>
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNodePackedIndices () const
  {
    return Kokkos::Compat::persistingView (k_lclInds1D_);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalRowCopy (LocalOrdinal localRow,
                   const Teuchos::ArrayView<LocalOrdinal>&indices,
                   size_t& numEntries) const
  {
    using Teuchos::ArrayView;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    const char tfecfFuncName[] = "getLocalRowCopy: ";

    TEUCHOS_TEST_FOR_EXCEPTION(
      isGloballyIndexed () && ! hasColMap (), std::runtime_error,
      "Tpetra::CrsGraph::getLocalRowCopy: The graph 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 "
      "graph doesn't have a column Map yet, you should call fillComplete on "
      "it first.");
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo(), std::runtime_error,
      "Graph row information was deleted at fillComplete.");
#endif // HAVE_TPETRA_DEBUG

    // This does the right thing (reports an empty row) if the input
    // row is invalid.
    const RowInfo rowinfo = getRowInfo (localRow);
    // No side effects on error.
    const size_t theNumEntries = rowinfo.numEntries;
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (indices.size ()) < theNumEntries, std::runtime_error,
      "Specified storage (size==" << indices.size () << ") does not suffice "
      "to hold all " << theNumEntries << " entry/ies for this row.");
    numEntries = theNumEntries;

    if (rowinfo.localRow != Teuchos::OrdinalTraits<size_t>::invalid ()) {
      if (isLocallyIndexed ()) {
        ArrayView<const LO> lview = getLocalView (rowinfo);
        for (size_t j = 0; j < theNumEntries; ++j) {
          indices[j] = lview[j];
        }
      }
      else if (isGloballyIndexed ()) {
        ArrayView<const GO> gview = getGlobalView (rowinfo);
        for (size_t j = 0; j < theNumEntries; ++j) {
          indices[j] = colMap_->getLocalElement (gview[j]);
        }
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalRowCopy (GlobalOrdinal globalRow,
                    const Teuchos::ArrayView<GlobalOrdinal>& indices,
                    size_t& numEntries) const
  {
    using Teuchos::ArrayView;
    const char tfecfFuncName[] = "getGlobalRowCopy: ";
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error,
      "Graph row information was deleted at fillComplete.");
#endif // HAVE_TPETRA_DEBUG

    // This does the right thing (reports an empty row) if the input
    // row is invalid.
    const RowInfo rowinfo = getRowInfoFromGlobalRowIndex (globalRow);
    const size_t theNumEntries = rowinfo.numEntries;
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (indices.size ()) < theNumEntries, std::runtime_error,
      "Specified storage (size==" << indices.size () << ") does not suffice "
      "to hold all " << theNumEntries << " entry/ies for this row.");
    numEntries = theNumEntries; // first side effect

    if (rowinfo.localRow != Teuchos::OrdinalTraits<size_t>::invalid ()) {
      if (isLocallyIndexed ()) {
        ArrayView<const LocalOrdinal> lview = getLocalView (rowinfo);
        for (size_t j = 0; j < theNumEntries; ++j) {
          indices[j] = colMap_->getGlobalElement (lview[j]);
        }
      }
      else if (isGloballyIndexed ()) {
        ArrayView<const GlobalOrdinal> gview = getGlobalView (rowinfo);
        for (size_t j = 0; j < theNumEntries; ++j) {
          indices[j] = gview[j];
        }
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalRowView (LocalOrdinal localRow,
                   Teuchos::ArrayView<const LocalOrdinal>& indices) const
  {
    const char tfecfFuncName[] = "getLocalRowView: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isGloballyIndexed (), std::runtime_error, "The graph's indices are "
      "currently stored as global indices, so we cannot return a view with "
      "local column indices, whether or not the graph has a column Map.  If "
      "the graph _does_ have a column Map, use getLocalRowCopy() instead.");
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error, "Graph row information was "
      "deleted at fillComplete().");
#endif // HAVE_TPETRA_DEBUG

    // This does the right thing (reports an empty row) if the input
    // row is invalid.
    const RowInfo rowInfo = getRowInfo (localRow);
    indices = Teuchos::null;
    if (rowInfo.localRow != Teuchos::OrdinalTraits<size_t>::invalid () &&
        rowInfo.numEntries > 0) {
      indices = this->getLocalView (rowInfo);
      // getLocalView returns a view of the _entire_ row, including
      // any extra space at the end (which 1-D unpacked storage
      // might have, for example).  That's why we have to take a
      // subview of the returned view.
      indices = indices (0, rowInfo.numEntries);
    }

#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (static_cast<size_t> (indices.size ()) !=
       getNumEntriesInLocalRow (localRow), std::logic_error, "indices.size() "
       "= " << indices.size () << " != getNumEntriesInLocalRow(localRow=" <<
       localRow << ") = " << getNumEntriesInLocalRow (localRow) <<
       ".  Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getGlobalRowView (GlobalOrdinal globalRow,
                    Teuchos::ArrayView<const GlobalOrdinal>& indices) const
  {
    const char tfecfFuncName[] = "getGlobalRowView: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isLocallyIndexed (), std::runtime_error, "The graph's indices are "
      "currently stored as local indices, so we cannot return a view with "
      "global column indices.  Use getGlobalRowCopy() instead.");
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error,
      "Graph row information was deleted at fillComplete().");
#endif // HAVE_TPETRA_DEBUG

    // This does the right thing (reports an empty row) if the input
    // row is invalid.
    const RowInfo rowInfo = getRowInfoFromGlobalRowIndex (globalRow);
    indices = Teuchos::null;
    if (rowInfo.localRow != Teuchos::OrdinalTraits<size_t>::invalid () &&
        rowInfo.numEntries > 0) {
      indices = (this->getGlobalView (rowInfo)) (0, rowInfo.numEntries);
    }

#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (static_cast<size_t> (indices.size ()) != getNumEntriesInGlobalRow (globalRow),
       std::logic_error, "indices.size() = " << indices.size ()
       << " != getNumEntriesInGlobalRow(globalRow=" << globalRow << ") = "
       << getNumEntriesInGlobalRow (globalRow)
       << ".  Please report this bug to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertLocalIndices (const LocalOrdinal localRow,
                      const Teuchos::ArrayView<const LocalOrdinal>& indices)
  {
    const char tfecfFuncName[] = "insertLocalIndices";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! isFillActive (), std::runtime_error,
      ": requires that fill is active.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isGloballyIndexed (), std::runtime_error,
      ": graph indices are global; use insertGlobalIndices().");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasColMap (), std::runtime_error,
      ": cannot insert local indices without a column map.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! rowMap_->isNodeLocalElement (localRow), std::runtime_error,
      ": row does not belong to this node.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error,
      ": graph row information was deleted at fillComplete().");
    if (! indicesAreAllocated ()) {
      allocateIndices (LocalIndices);
    }

#ifdef HAVE_TPETRA_DEBUG
    // In a debug build, if the graph 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 ()) {
      using Teuchos::Array;
      using Teuchos::toString;
      using std::endl;
      typedef typename Teuchos::ArrayView<const LocalOrdinal>::size_type size_type;

      const map_type& colMap = * (getColMap ());
      Array<LocalOrdinal> badColInds;
      bool allInColMap = true;
      for (size_type k = 0; k < indices.size (); ++k) {
        if (! colMap.isNodeLocalElement (indices[k])) {
          allInColMap = false;
          badColInds.push_back (indices[k]);
        }
      }
      if (! allInColMap) {
        std::ostringstream os;
        os << "Tpetra::CrsMatrix::insertLocalIndices: 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 graph 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

    insertLocalIndicesImpl (localRow, indices);

#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      indicesAreAllocated() == false || isLocallyIndexed() == false,
      std::logic_error,
      ": Violated stated post-conditions. Please contact Tpetra team.");
#endif
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertLocalIndices (const LocalOrdinal localRow,
                      const LocalOrdinal numEnt,
                      const LocalOrdinal inds[])
  {
    Teuchos::ArrayView<const LocalOrdinal> indsT (inds, numEnt);
    this->insertLocalIndices (localRow, indsT);
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertLocalIndicesFiltered (const LocalOrdinal localRow,
                              const Teuchos::ArrayView<const LocalOrdinal>& indices)
  {
    typedef LocalOrdinal LO;
    const char tfecfFuncName[] = "insertLocalIndicesFiltered";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillActive() == false, std::runtime_error,
      ": requires that fill is active.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isGloballyIndexed() == true, std::runtime_error,
      ": graph indices are global; use insertGlobalIndices().");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      hasColMap() == false, std::runtime_error,
      ": cannot insert local indices without a column map.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      rowMap_->isNodeLocalElement(localRow) == false, std::runtime_error,
      ": row does not belong to this node.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error,
      ": graph row information was deleted at fillComplete().");
    if (! indicesAreAllocated ()) {
      allocateIndices (LocalIndices);
    }

     // If we have a column map, use it to filter the entries.
    if (hasColMap ()) {
      Teuchos::Array<LO> filtered_indices (indices);
      SLocalGlobalViews inds_view;
      SLocalGlobalNCViews inds_ncview;
      inds_ncview.linds = filtered_indices();
      const size_t numFilteredEntries =
        filterIndices<LocalIndices>(inds_ncview);
      inds_view.linds = filtered_indices (0, numFilteredEntries);
      insertLocalIndicesImpl(localRow, inds_view.linds);
    }
    else {
      insertLocalIndicesImpl(localRow, indices);
    }
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      indicesAreAllocated() == false || isLocallyIndexed() == false,
      std::logic_error,
      ": Violated stated post-conditions. Please contact Tpetra team.");
#endif
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertGlobalIndices (const GlobalOrdinal grow,
                       const Teuchos::ArrayView<const GlobalOrdinal>& indices)
  {
    using Teuchos::Array;
    using Teuchos::ArrayView;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    typedef typename ArrayView<const GO>::size_type size_type;
    const char tfecfFuncName[] = "insertGlobalIndices";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isLocallyIndexed() == true, std::runtime_error,
      ": graph indices are local; use insertLocalIndices().");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error,
      ": graph row information was deleted at fillComplete().");
    // This can't really be satisfied for now, because if we are
    // fillComplete(), then we are local.  In the future, this may
    // change.  However, the rule that modification require active
    // fill will not change.
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillActive() == false, std::runtime_error,
      ": You are not allowed to call this method if fill is not active.  "
      "If fillComplete has been called, you must first call resumeFill "
      "before you may insert indices.");
    if (! indicesAreAllocated ()) {
      allocateIndices (GlobalIndices);
    }
    const LO myRow = rowMap_->getLocalElement (grow);
    if (myRow != Teuchos::OrdinalTraits<LO>::invalid ()) {
#ifdef HAVE_TPETRA_DEBUG
      if (hasColMap ()) {
        using std::endl;
        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.
        Array<GO> badColInds;
        bool allInColMap = true;
        for (size_type k = 0; k < indices.size (); ++k) {
          if (! colMap.isNodeGlobalElement (indices[k])) {
            allInColMap = false;
            badColInds.push_back (indices[k]);
          }
        }
        if (! allInColMap) {
          std::ostringstream os;
          os << "Tpetra::CrsGraph::insertGlobalIndices: You attempted to insert "
            "entries in owned row " << grow << ", 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
      insertGlobalIndicesImpl (myRow, indices);
    }
    else { // a nonlocal row
      const size_type numIndices = indices.size ();
      // This creates the Array if it doesn't exist yet.  std::map's
      // operator[] does a lookup each time, so it's better to pull
      // nonlocals_[grow] out of the loop.
      std::vector<GO>& nonlocalRow = nonlocals_[grow];
      for (size_type k = 0; k < numIndices; ++k) {
        nonlocalRow.push_back (indices[k]);
      }
    }
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      indicesAreAllocated() == false || isGloballyIndexed() == false,
      std::logic_error,
      ": Violated stated post-conditions. Please contact Tpetra team.");
#endif
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertGlobalIndices (const GlobalOrdinal globalRow,
                       const LocalOrdinal numEnt,
                       const GlobalOrdinal inds[])
  {
    Teuchos::ArrayView<const GlobalOrdinal> indsT (inds, numEnt);
    this->insertGlobalIndices (globalRow, indsT);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  insertGlobalIndicesFiltered (const GlobalOrdinal grow,
                               const Teuchos::ArrayView<const GlobalOrdinal>& indices)
  {
    using Teuchos::Array;
    using Teuchos::ArrayView;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    const char tfecfFuncName[] = "insertGlobalIndicesFiltered";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isLocallyIndexed() == true, std::runtime_error,
      ": graph indices are local; use insertLocalIndices().");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasRowInfo (), std::runtime_error,
      ": graph row information was deleted at fillComplete().");
    // This can't really be satisfied for now, because if we are
    // fillComplete(), then we are local.  In the future, this may
    // change.  However, the rule that modification require active
    // fill will not change.
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillActive() == false, std::runtime_error,
      ": You are not allowed to call this method if fill is not active.  "
      "If fillComplete has been called, you must first call resumeFill "
      "before you may insert indices.");
    if (! indicesAreAllocated ()) {
      allocateIndices (GlobalIndices);
    }
    const LO myRow = rowMap_->getLocalElement (grow);
    if (myRow != Teuchos::OrdinalTraits<LO>::invalid ()) {
      // If we have a column map, use it to filter the entries.
      if (hasColMap ()) {
        Array<GO> filtered_indices(indices);
        SLocalGlobalViews inds_view;
        SLocalGlobalNCViews inds_ncview;
        inds_ncview.ginds = filtered_indices();
        const size_t numFilteredEntries =
          filterIndices<GlobalIndices> (inds_ncview);
        inds_view.ginds = filtered_indices (0, numFilteredEntries);
        insertGlobalIndicesImpl(myRow, inds_view.ginds);
      }
      else {
       insertGlobalIndicesImpl(myRow, indices);
      }
    }
    else { // a nonlocal row
      typedef typename ArrayView<const GO>::size_type size_type;
      const size_type numIndices = indices.size ();
      for (size_type k = 0; k < numIndices; ++k) {
        nonlocals_[grow].push_back (indices[k]);
      }
    }
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      indicesAreAllocated() == false || isGloballyIndexed() == false,
      std::logic_error,
      ": Violated stated post-conditions. Please contact Tpetra team.");
#endif
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  removeLocalIndices (LocalOrdinal lrow)
  {
    const char tfecfFuncName[] = "removeLocalIndices: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! isFillActive (), std::runtime_error, "requires that fill is active.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isStorageOptimized (), std::runtime_error,
      "cannot remove indices after optimizeStorage() has been called.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isGloballyIndexed (), std::runtime_error, "graph indices are global.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! rowMap_->isNodeLocalElement (lrow), std::runtime_error,
      "Local row " << lrow << " is not in the row Map on the calling process.");
    if (! indicesAreAllocated ()) {
      allocateIndices (LocalIndices);
    }

    // FIXME (mfh 13 Aug 2014) What if they haven't been cleared on
    // all processes?
    clearGlobalConstants ();

    if (k_numRowEntries_.dimension_0 () != 0) {
      const size_t oldNumEntries = k_numRowEntries_(lrow);
      nodeNumEntries_ -= oldNumEntries;
      k_numRowEntries_(lrow) = 0;
    }
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      getNumEntriesInLocalRow (lrow) != 0 ||
      ! indicesAreAllocated () ||
      ! isLocallyIndexed (), std::logic_error,
      ": Violated stated post-conditions. Please contact Tpetra team.");
#endif // HAVE_TPETRA_DEBUG
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  setAllIndices (const typename local_graph_type::row_map_type& rowPointers,
                 const typename local_graph_type::entries_type::non_const_type& columnIndices)
  {
    const char tfecfFuncName[] = "setAllIndices: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! hasColMap () || getColMap ().is_null (), std::runtime_error,
      "The graph must have a column Map before you may call this method.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (rowPointers.size ()) != this->getNodeNumRows () + 1,
      std::runtime_error, "rowPointers.size() = " << rowPointers.size () <<
      " != this->getNodeNumRows()+1 = " << (this->getNodeNumRows () + 1) <<
      ".");

    // FIXME (mfh 07 Aug 2014) We need to relax this restriction,
    // since the future model will be allocation at construction, not
    // lazy allocation on first insert.
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      k_lclInds1D_.dimension_0 () != 0 || k_gblInds1D_.dimension_0 () != 0,
      std::runtime_error, "You may not call this method if 1-D data structures "
      "are already allocated.");

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      lclInds2D_ != Teuchos::null || gblInds2D_ != Teuchos::null,
      std::runtime_error, "You may not call this method if 2-D data structures "
      "are already allocated.");

    const size_t localNumEntries = rowPointers(getNodeNumRows ());

    indicesAreAllocated_ = true;
    indicesAreLocal_     = true;
    pftype_              = StaticProfile; // if the profile wasn't static before, it sure is now.
    k_lclInds1D_         = columnIndices;
    k_rowPtrs_           = rowPointers;
    nodeNumAllocated_    = localNumEntries;
    nodeNumEntries_      = localNumEntries;

    // Build the local graph.
    lclGraph_ = local_graph_type (k_lclInds1D_, k_rowPtrs_);

    // These normally get cleared out at the end of allocateIndices.
    // It makes sense to clear them out here, because at the end of
    // this method, the graph is allocated on the calling process.
    numAllocForAllRows_ = 0;
    k_numAllocPerRow_ = decltype (k_numAllocPerRow_) ();

    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  setAllIndices (const Teuchos::ArrayRCP<size_t>& rowPointers,
                 const Teuchos::ArrayRCP<LocalOrdinal>& columnIndices)
  {
    using Kokkos::View;
    typedef typename local_graph_type::row_map_type row_map_type;
    typedef typename row_map_type::array_layout layout_type;
    typedef typename row_map_type::non_const_value_type row_offset_type;
    typedef View<size_t*, layout_type , Kokkos::HostSpace,
      Kokkos::MemoryUnmanaged> input_view_type;
    typedef typename row_map_type::non_const_type nc_row_map_type;

    const size_t size = static_cast<size_t> (rowPointers.size ());
    const bool same = Kokkos::Impl::is_same<size_t, row_offset_type>::value;
    input_view_type ptr_in (rowPointers.getRawPtr (), size);

    nc_row_map_type ptr_rot ("Tpetra::CrsGraph::ptr", size);

    if (same) { // size_t == row_offset_type
      // This compile-time logic ensures that the compiler never sees
      // an assignment of View<row_offset_type*, ...> to View<size_t*,
      // ...> unless size_t == row_offset_type.
      input_view_type ptr_decoy (rowPointers.getRawPtr (), size); // never used
      Kokkos::deep_copy (Kokkos::Impl::if_c<same,
                           nc_row_map_type,
                           input_view_type>::select (ptr_rot, ptr_decoy),
                         ptr_in);
    }
    else { // size_t != row_offset_type
      // CudaUvmSpace != HostSpace, so this will be false in that case.
      const bool inHostMemory =
        Kokkos::Impl::is_same<typename row_map_type::memory_space,
          Kokkos::HostSpace>::value;
      if (inHostMemory) {
        // Copy (with cast from size_t to row_offset_type, with bounds
        // checking if necessary) to ptr_rot.
        ::Tpetra::Details::copyOffsets (ptr_rot, ptr_in);
      }
      else { // Copy input row offsets to device first.
        //
        // FIXME (mfh 24 Mar 2015) If CUDA UVM, running in the host's
        // execution space would avoid the double copy.
        //
        View<size_t*, layout_type ,execution_space > ptr_st ("Tpetra::CrsGraph::ptr", size);
        Kokkos::deep_copy (ptr_st, ptr_in);
        // Copy on device (casting from size_t to row_offset_type,
        // with bounds checking if necessary) to ptr_rot.  This
        // executes in the output View's execution space, which is the
        // same as execution_space.
        ::Tpetra::Details::copyOffsets (ptr_rot, ptr_st);
      }
    }

    Kokkos::View<LocalOrdinal*, layout_type , execution_space > k_ind =
      Kokkos::Compat::getKokkosViewDeepCopy<device_type> (columnIndices ());
    setAllIndices (ptr_rot, k_ind);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getNumEntriesPerLocalRowUpperBound (Teuchos::ArrayRCP<const size_t>& boundPerLocalRow,
                                      size_t& boundForAllLocalRows,
                                      bool& boundSameForAllLocalRows) const
  {
    // The three output arguments.  We assign them to the actual
    // output arguments at the end, in order to implement
    // transactional semantics.
    Teuchos::ArrayRCP<const size_t> numEntriesPerRow;
    size_t numEntriesForAll = 0;
    bool allRowsSame = true;

    const ptrdiff_t numRows = static_cast<ptrdiff_t> (this->getNodeNumRows ());

    if (! this->indicesAreAllocated ()) {
      if (k_numAllocPerRow_.dimension_0 () != 0) {
        // This is a shallow copy; the ArrayRCP wraps the View in a
        // custom destructor, which ensures correct deallocation if
        // that is the only reference to the View.  Furthermore, this
        // View is a host View, so this doesn't assume UVM.
        numEntriesPerRow = Kokkos::Compat::persistingView (k_numAllocPerRow_);
        allRowsSame = false; // conservatively; we don't check the array
      }
      else {
        numEntriesForAll = numAllocForAllRows_;
        allRowsSame = true;
      }
    }
    else if (k_numRowEntries_.dimension_0 () != 0) {
      // This is a shallow copy; the ArrayRCP wraps the View in a
      // custom destructor, which ensures correct deallocation if that
      // is the only reference to the View.  Furthermore, this View is
      // a host View, so this doesn't assume UVM.
      numEntriesPerRow = Kokkos::Compat::persistingView (k_numRowEntries_);
      allRowsSame = false; // conservatively; we don't check the array
    }
    else if (this->nodeNumAllocated_ == 0) {
      numEntriesForAll = 0;
      allRowsSame = true;
    }
    else {
      // left with the case that we have optimized storage. in this
      // case, we have to construct a list of row sizes.
      TEUCHOS_TEST_FOR_EXCEPTION(
        this->getProfileType () != StaticProfile, std::logic_error,
        "Tpetra::CrsGraph::getNumEntriesPerRowUpperBound: "
        "The graph is not StaticProfile, but storage appears to be optimized.  "
        "Please report this bug to the Tpetra developers.");
      TEUCHOS_TEST_FOR_EXCEPTION(
        numRows != 0 && k_rowPtrs_.dimension_0 () == 0, std::logic_error,
        "Tpetra::CrsGraph::getNumEntriesPerRowUpperBound: "
        "The graph has " << numRows << " (> 0) row" << (numRows != 1 ? "s" : "")
        << " on the calling process, but the k_rowPtrs_ array has zero entries.  "
        "Please report this bug to the Tpetra developers.");

      Teuchos::ArrayRCP<size_t> numEnt;
      if (numRows != 0) {
        numEnt = Teuchos::arcp<size_t> (numRows);
      }

      // We have to iterate through the row offsets anyway, so we
      // might as well check whether all rows' bounds are the same.
      bool allRowsReallySame = false;
      for (ptrdiff_t i = 0; i < numRows; ++i) {
        numEnt[i] = k_rowPtrs_(i+1) - k_rowPtrs_(i);
        if (i != 0 && numEnt[i] != numEnt[i-1]) {
          allRowsReallySame = false;
        }
      }
      if (allRowsReallySame) {
        if (numRows == 0) {
          numEntriesForAll = 0;
        } else {
          numEntriesForAll = numEnt[1] - numEnt[0];
        }
        allRowsSame = true;
      }
      else {
        numEntriesPerRow = numEnt; // Teuchos::arcp_const_cast<const size_t> (numEnt);
        allRowsSame = false; // conservatively; we don't check the array
      }
    }

    TEUCHOS_TEST_FOR_EXCEPTION(
      numEntriesForAll != 0 && numEntriesPerRow.size () != 0, std::logic_error,
      "Tpetra::CrsGraph::getNumEntriesPerLocalRowUpperBound: "
      "numEntriesForAll and numEntriesPerRow are not consistent.  The former "
      "is nonzero (" << numEntriesForAll << "), but the latter has nonzero "
      "size " << numEntriesPerRow.size () << ".  "
      "Please report this bug to the Tpetra developers.");
    TEUCHOS_TEST_FOR_EXCEPTION(
      numEntriesForAll != 0 && ! allRowsSame, std::logic_error,
      "Tpetra::CrsGraph::getNumEntriesPerLocalRowUpperBound: "
      "numEntriesForAll and allRowsSame are not consistent.  The former "
      "is nonzero (" << numEntriesForAll << "), but the latter is false.  "
      "Please report this bug to the Tpetra developers.");
    TEUCHOS_TEST_FOR_EXCEPTION(
      numEntriesPerRow.size () != 0 && allRowsSame, std::logic_error,
      "Tpetra::CrsGraph::getNumEntriesPerLocalRowUpperBound: "
      "numEntriesPerRow and allRowsSame are not consistent.  The former has "
      "nonzero length " << numEntriesForAll << ", but the latter is true.  "
      "Please report this bug to the Tpetra developers.");

    boundPerLocalRow = numEntriesPerRow;
    boundForAllLocalRows = numEntriesForAll;
    boundSameForAllLocalRows = allRowsSame;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  globalAssemble ()
  {
    using Teuchos::Comm;
    using Teuchos::outArg;
    using Teuchos::RCP;
    using Teuchos::rcp;
    using Teuchos::REDUCE_MAX;
    using Teuchos::REDUCE_MIN;
    using Teuchos::reduceAll;
    typedef CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic> crs_graph_type;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    typedef typename Teuchos::Array<GO>::size_type size_type;
    const char tfecfFuncName[] = "globalAssemble: "; // for exception macro

    RCP<const Comm<int> > comm = getComm ();

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (! isFillActive (), std::runtime_error, "Fill must be active before "
       "you may call this method.");

    const size_t myNumNonlocalRows = nonlocals_.size ();

    // If no processes have nonlocal rows, then we don't have to do
    // anything.  Checking this is probably cheaper than constructing
    // the Map of nonlocal rows (see below) and noticing that it has
    // zero global entries.
    {
      const int iHaveNonlocalRows = (myNumNonlocalRows == 0) ? 0 : 1;
      int someoneHasNonlocalRows = 0;
      reduceAll<int, int> (*comm, REDUCE_MAX, iHaveNonlocalRows,
                           outArg (someoneHasNonlocalRows));
      if (someoneHasNonlocalRows == 0) {
        return; // no process has nonlocal rows, so nothing to do
      }
    }

    // 1. Create a list of the "nonlocal" rows on each process.  this
    //    requires iterating over nonlocals_, so while we do this,
    //    deduplicate the entries and get a count for each nonlocal
    //    row on this process.
    // 2. Construct a new row Map corresponding to those rows.  This
    //    Map is likely overlapping.  We know that the Map is not
    //    empty on all processes, because the above all-reduce and
    //    return exclude that case.

    RCP<const map_type> nonlocalRowMap;
    // Keep this for CrsGraph's constructor, so we can use StaticProfile.
    Teuchos::ArrayRCP<size_t> numEntPerNonlocalRow (myNumNonlocalRows);
    {
      Teuchos::Array<GO> myNonlocalGblRows (myNumNonlocalRows);
      size_type curPos = 0;
      for (auto mapIter = nonlocals_.begin (); mapIter != nonlocals_.end ();
           ++mapIter, ++curPos) {
        myNonlocalGblRows[curPos] = mapIter->first;
        std::vector<GO>& gblCols = mapIter->second; // by ref; change in place
        std::sort (gblCols.begin (), gblCols.end ());
        auto vecLast = std::unique (gblCols.begin (), gblCols.end ());
        gblCols.erase (vecLast, gblCols.end ());
        numEntPerNonlocalRow[curPos] = gblCols.size ();
      }

      // Currently, Map requires that its indexBase be the global min
      // of all its global indices.  Map won't compute this for us, so
      // we must do it.  If our process has no nonlocal rows, set the
      // "min" to the max possible GO value.  This ensures that if
      // some process has at least one nonlocal row, then it will pick
      // that up as the min.  We know that at least one process has a
      // nonlocal row, since the all-reduce and return at the top of
      // this method excluded that case.
      GO myMinNonlocalGblRow = std::numeric_limits<GO>::max ();
      {
        auto iter = std::min_element (myNonlocalGblRows.begin (),
                                      myNonlocalGblRows.end ());
        if (iter != myNonlocalGblRows.end ()) {
          myMinNonlocalGblRow = *iter;
        }
      }
      GO gblMinNonlocalGblRow = 0;
      reduceAll<int, GO> (*comm, REDUCE_MIN, myMinNonlocalGblRow,
                          outArg (gblMinNonlocalGblRow));
      const GO indexBase = gblMinNonlocalGblRow;
      const global_size_t INV = Teuchos::OrdinalTraits<global_size_t>::invalid ();
      nonlocalRowMap = rcp (new map_type (INV, myNonlocalGblRows (), indexBase, comm));
    }

    // 3. Use the column indices for each nonlocal row, as stored in
    //    nonlocals_, to construct a CrsGraph corresponding to
    //    nonlocal rows.  We may use StaticProfile, since we have
    //    exact counts of the number of entries in each nonlocal row.

    RCP<crs_graph_type> nonlocalGraph =
      rcp (new crs_graph_type (nonlocalRowMap, numEntPerNonlocalRow,
                               StaticProfile));
    {
      size_type curPos = 0;
      for (auto mapIter = nonlocals_.begin (); mapIter != nonlocals_.end ();
           ++mapIter, ++curPos) {
        const GO gblRow = mapIter->first;
        std::vector<GO>& gblCols = mapIter->second; // by ref just to avoid copy
        const LO numEnt = static_cast<LO> (numEntPerNonlocalRow[curPos]);
        nonlocalGraph->insertGlobalIndices (gblRow, numEnt, gblCols.data ());
      }
    }
    // There's no need to fill-complete the nonlocals graph.
    // We just use it as a temporary container for the Export.

    // 4. If the original row Map is one to one, then we can Export
    //    directly from nonlocalGraph into this.  Otherwise, we have
    //    to create a temporary graph with a one-to-one row Map,
    //    Export into that, then Import from the temporary graph into
    //    *this.

    auto origRowMap = this->getRowMap ();
    const bool origRowMapIsOneToOne = origRowMap->isOneToOne ();

    if (origRowMapIsOneToOne) {
      export_type exportToOrig (nonlocalRowMap, origRowMap);
      this->doExport (*nonlocalGraph, exportToOrig, Tpetra::INSERT);
      // We're done at this point!
    }
    else {
      // If you ask a Map whether it is one to one, it does some
      // communication and stashes intermediate results for later use
      // by createOneToOne.  Thus, calling createOneToOne doesn't cost
      // much more then the original cost of calling isOneToOne.
      auto oneToOneRowMap = Tpetra::createOneToOne (origRowMap);
      export_type exportToOneToOne (nonlocalRowMap, oneToOneRowMap);

      // Create a temporary graph with the one-to-one row Map.
      //
      // TODO (mfh 09 Sep 2016) Estimate the number of entries in each
      // row, to avoid reallocation during the Export operation.
      crs_graph_type oneToOneGraph (oneToOneRowMap, 0);
      // Export from graph of nonlocals into the temp one-to-one graph.
      oneToOneGraph.doExport (*nonlocalGraph, exportToOneToOne, Tpetra::INSERT);

      // We don't need the graph of nonlocals anymore, so get rid of
      // it, to keep the memory high-water mark down.
      nonlocalGraph = Teuchos::null;

      // Import from the one-to-one graph to the original graph.
      import_type importToOrig (oneToOneRowMap, origRowMap);
      this->doImport (oneToOneGraph, importToOrig, Tpetra::INSERT);
    }

    // It's safe now to clear out nonlocals_, since we've already
    // committed side effects to *this.  The standard idiom for
    // clearing a Container like std::map, is to swap it with an empty
    // Container and let the swapped Container fall out of scope.
    decltype (nonlocals_) newNonlocals;
    std::swap (nonlocals_, newNonlocals);

    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  resumeFill (const Teuchos::RCP<Teuchos::ParameterList>& params)
  {
    const char tfecfFuncName[] = "resumeFill";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! hasRowInfo(), std::runtime_error,
      ": Sorry, you cannot resume fill of the CrsGraph, since the graph's row "
      "information was deleted in fillComplete().");

#ifdef HAVE_TPETRA_DEBUG
    Teuchos::barrier( *rowMap_->getComm() );
#endif // HAVE_TPETRA_DEBUG
    clearGlobalConstants();
    if (params != Teuchos::null) this->setParameterList (params);
    lowerTriangular_  = false;
    upperTriangular_  = false;
    // either still sorted/merged or initially sorted/merged
    indicesAreSorted_ = true;
    noRedundancies_ = true;
    fillComplete_ = false;
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      ! isFillActive() || isFillComplete(), std::logic_error,
      "::resumeFill(): At end of method, either fill is not active or fill is "
      "complete.  This violates stated post-conditions.  Please report this bug "
      "to the Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  fillComplete (const Teuchos::RCP<Teuchos::ParameterList>& params)
  {
    // If the graph already has domain and range Maps, don't clobber
    // them.  If it doesn't, use the current row Map for both the
    // domain and range Maps.
    //
    // NOTE (mfh 28 Sep 2014): If the graph was constructed without a
    // column Map, and column indices are inserted which are not in
    // the row Map on any process, this will cause troubles.  However,
    // that is not a common case for most applications that we
    // encounter, and checking for it might require more
    // communication.
    Teuchos::RCP<const map_type> domMap = this->getDomainMap ();
    if (domMap.is_null ()) {
      domMap = this->getRowMap ();
    }
    Teuchos::RCP<const map_type> ranMap = this->getRangeMap ();
    if (ranMap.is_null ()) {
      ranMap = this->getRowMap ();
    }
    this->fillComplete (domMap, ranMap, params);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<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)
  {
    const char tfecfFuncName[] = "fillComplete";

#ifdef HAVE_TPETRA_DEBUG
    rowMap_->getComm ()->barrier ();
#endif // HAVE_TPETRA_DEBUG

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( ! isFillActive() || isFillComplete(),
      std::runtime_error, ": Graph fill state must be active (isFillActive() "
      "must be true) before calling fillComplete().");

    const int numProcs = getComm ()->getSize ();

    //
    // Read and set parameters
    //

    // Does the caller want to sort remote GIDs (within those owned by
    // the same process) in makeColMap()?
    if (! params.is_null ()) {
      if (params->isParameter ("sort column map ghost gids")) {
        sortGhostsAssociatedWithEachProcessor_ =
          params->get<bool> ("sort column map ghost gids",
                             sortGhostsAssociatedWithEachProcessor_);
      }
      else if (params->isParameter ("Sort column Map ghost GIDs")) {
        sortGhostsAssociatedWithEachProcessor_ =
          params->get<bool> ("Sort column Map ghost GIDs",
                             sortGhostsAssociatedWithEachProcessor_);
      }
    }

    // If true, the caller promises that no process did nonlocal
    // changes since the last call to fillComplete.
    bool assertNoNonlocalInserts = false;
    if (! params.is_null ()) {
      assertNoNonlocalInserts =
        params->get<bool> ("No Nonlocal Changes", assertNoNonlocalInserts);
    }

    //
    // Allocate indices, if they haven't already been allocated
    //
    if (! indicesAreAllocated ()) {
      if (hasColMap ()) {
        // We have a column Map, so use local indices.
        allocateIndices (LocalIndices);
      } else {
        // We don't have a column Map, so use global indices.
        allocateIndices (GlobalIndices);
      }
    }

    //
    // Do global assembly, if requested and if the communicator
    // contains more than one process.
    //
    const bool mayNeedGlobalAssemble = ! assertNoNonlocalInserts && numProcs > 1;
    if (mayNeedGlobalAssemble) {
      // This first checks if we need to do global assembly.
      // The check costs a single all-reduce.
      globalAssemble ();
    }
    else {
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        numProcs > 1 && nonlocals_.size() > 0, std::runtime_error,
        ":" << std::endl << "The graph's communicator contains only one "
        "process, but there are nonlocal entries.  " << std::endl <<
        "This probably means that invalid entries were added to the graph.");
    }

    // Set domain and range Map.  This may clear the Import / Export
    // objects if the new Maps differ from any old ones.
    setDomainRangeMaps (domainMap, rangeMap);

    // If the graph does not already have a column Map (either from
    // the user constructor calling the version of the constructor
    // that takes a column Map, or from a previous fillComplete call),
    // then create it.
    if (! hasColMap ()) {
      makeColMap ();
    }

    // Make indices local, if they aren't already.
    // The method doesn't do any work if the indices are already local.
    makeIndicesLocal ();

    if (! isSorted ()) {
      // If this process has no indices, then CrsGraph considers it
      // already trivially sorted.  Thus, this method need not be
      // called on all processes in the row Map's communicator.
      sortAllIndices ();
    }

    if (! isMerged()) {
      mergeAllIndices ();
    }
    makeImportExport (); // Make Import and Export objects, if necessary
    computeGlobalConstants ();
    fillLocalGraph (params);
    fillComplete_ = true;

#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillActive() == true || isFillComplete() == false, std::logic_error,
      ": Violated stated post-conditions. Please contact Tpetra team.");
#endif

    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<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>& params)
  {
    const char tfecfFuncName[] = "expertStaticFillComplete: ";
#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-G-Setup"))));
#endif


    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      domainMap.is_null () || rangeMap.is_null (),
      std::runtime_error, "The input domain Map and range Map must be nonnull.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      pftype_ != StaticProfile, std::runtime_error, "You may not call this "
      "method unless the graph is StaticProfile.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillComplete () || ! hasColMap (), std::runtime_error, "You may not "
      "call this method unless the graph has a column Map.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      getNodeNumRows () > 0 && k_rowPtrs_.dimension_0 () == 0,
      std::runtime_error, "The calling process has getNodeNumRows() = "
      << getNodeNumRows () << " > 0 rows, but the row offsets array has not "
      "been set.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      static_cast<size_t> (k_rowPtrs_.dimension_0 ()) != getNodeNumRows () + 1,
      std::runtime_error, "The row offsets array has length " <<
      k_rowPtrs_.dimension_0 () << " != getNodeNumRows()+1 = " <<
      (getNodeNumRows () + 1) << ".");

    // Note: We don't need to do the following things which are normally done in fillComplete:
    // allocateIndices, globalAssemble, makeColMap, makeIndicesLocal, sortAllIndices, mergeAllIndices

    // Note: Need to do this so computeGlobalConstants & fillLocalGraph work
    //
    // The first assignment is always true if the graph has 1-D
    // storage (StaticProfile).  The second assignment is only true if
    // storage is packed.
    nodeNumAllocated_ = k_rowPtrs_(getNodeNumRows ());
    nodeNumEntries_ = nodeNumAllocated_;

    // Constants from allocateIndices
    //
    // mfh 08 Aug 2014: numAllocForAllRows_ and k_numAllocPerRow_ go
    // away once the graph is allocated.  expertStaticFillComplete
    // either presumes that the graph is allocated, or "allocates" it.
    //
    // FIXME (mfh 08 Aug 2014) The goal for the Kokkos refactor
    // version of CrsGraph is to allocate in the constructor, not
    // lazily on first insert.  That will make both
    // numAllocForAllRows_ and k_numAllocPerRow_ obsolete.
    numAllocForAllRows_  = 0;
    k_numAllocPerRow_    = decltype (k_numAllocPerRow_) ();
    indicesAreAllocated_ = true;

    // Constants from makeIndicesLocal
    //
    // The graph has a column Map, so its indices had better be local.
    indicesAreLocal_  = true;
    indicesAreGlobal_ = false;

    // set domain/range map: may clear the import/export objects
#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-Maps"))));
#endif
    setDomainRangeMaps (domainMap, rangeMap);

    // Presume the user sorted and merged the arrays first
    indicesAreSorted_ = true;
    noRedundancies_ = true;

    // makeImportExport won't create a new importer/exporter if I set one here first.
#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-mIXcheckI"))));
#endif

    importer_ = Teuchos::null;
    exporter_ = Teuchos::null;
    if (importer != Teuchos::null) {
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        ! importer->getSourceMap ()->isSameAs (*getDomainMap ()) ||
        ! importer->getTargetMap ()->isSameAs (*getColMap ()),
        std::invalid_argument,": importer does not match matrix maps.");
      importer_ = importer;

    }

#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-mIXcheckE"))));
#endif

    if (exporter != Teuchos::null) {
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
        ! exporter->getSourceMap ()->isSameAs (*getRowMap ()) ||
        ! exporter->getTargetMap ()->isSameAs (*getRangeMap ()),
        std::invalid_argument,": exporter does not match matrix maps.");
      exporter_ = exporter;
    }

#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-mIXmake"))));
#endif

    makeImportExport ();

    // Compute the constants
#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-cGC"))));
#endif
    computeGlobalConstants ();

    // Since we have a StaticProfile, fillLocalGraph will do the right thing...
#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-fLG"))));
#endif
    fillLocalGraph (params);
    fillComplete_ = true;

#ifdef HAVE_TPETRA_MMM_TIMINGS
    MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("ESFC-G-cIS"))));
#endif
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  fillLocalGraph (const Teuchos::RCP<Teuchos::ParameterList>& params)
  {
    using ::Tpetra::Details::computeOffsetsFromCounts;
    using Kokkos::create_mirror_view;
    typedef decltype (k_numRowEntries_) row_entries_type;
    typedef typename 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_graph_type::entries_type::non_const_type lclinds_1d_type;
#ifdef HAVE_TPETRA_DEBUG
    const char tfecfFuncName[] = "fillLocalGraph (called from fillComplete or "
      "expertStaticFillComplete): ";
#endif // HAVE_TPETRA_DEBUG
    const size_t lclNumRows = this->getNodeNumRows ();

    // This method's goal is to fill in the two arrays (compressed
    // sparse row format) that define the sparse graph's structure.
    //
    // Use the nonconst version of row_map_type for ptr_d, because
    // the latter is const and we need to modify ptr_d here.
    non_const_row_map_type ptr_d;
    row_map_type ptr_d_const;
    lclinds_1d_type ind_d;

    bool requestOptimizedStorage = true;
    if (! params.is_null () && ! params->get ("Optimize Storage", true)) {
      requestOptimizedStorage = false;
    }
    if (getProfileType () == DynamicProfile) {
      // Pack 2-D storage (DynamicProfile) into 1-D packed storage.
      //
      // DynamicProfile means that the graph's column indices are
      // currently stored in a 2-D "unpacked" format, in the
      // arrays-of-arrays lclInds2D_.  We allocate 1-D storage
      // (ind_d) and then copy from 2-D storage (lclInds2D_) into 1-D
      // storage (ind_d).
#ifdef HAVE_TPETRA_DEBUG
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
        (static_cast<size_t> (k_numRowEntries_.dimension_0 ()) != lclNumRows,
         std::logic_error, "(DynamicProfile branch) "
         "k_numRowEntries_.dimension_0() = "
         << k_numRowEntries_.dimension_0 ()
         << " != getNodeNumRows() = " << lclNumRows << "");
#endif // HAVE_TPETRA_DEBUG

      // Pack the row offsets into ptr_d, by doing a sum-scan of the
      // array of valid entry counts per row (k_numRowEntries_).  The
      // pack method can handle its counts input being a host View.
      //
      // 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;
      {
        // Allocate the packed row offsets array.
        ptr_d = non_const_row_map_type ("Tpetra::CrsGraph::ptr", lclNumRows+1);
        typename row_entries_type::const_type numRowEnt_h = k_numRowEntries_;
        // This function can handle that numRowEnt_h lives on host.
        lclTotalNumEntries = computeOffsetsFromCounts (ptr_d, numRowEnt_h);
        ptr_d_const = ptr_d;
      }

#ifdef HAVE_TPETRA_DEBUG
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
        (static_cast<size_t> (ptr_d.dimension_0 ()) != lclNumRows + 1,
         std::logic_error, "(DynamicProfile branch) After packing ptr_d, "
         "ptr_d.dimension_0() = " << ptr_d.dimension_0 () << " != "
         "(lclNumRows+1) = " << (lclNumRows+1) << ".");
      {
        // mfh 26 Jun 2016: Don't assume UVM.  ptr_d lives in device
        // memory, so if we want to check its last entry on host, copy
        // it back to host explicitly.
        auto ptr_d_ent_d = Kokkos::subview (ptr_d, lclNumRows);
        auto ptr_d_ent_h = create_mirror_view (ptr_d_ent_d);
        Kokkos::deep_copy (ptr_d_ent_h, ptr_d_ent_d);
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (ptr_d_ent_h () != lclTotalNumEntries, std::logic_error,
           "(DynamicProfile branch) After packing ptr_d, ptr_d(lclNumRows = "
           << lclNumRows << ") = " << ptr_d_ent_h () << " != total number of "
           "entries on the calling process = " << lclTotalNumEntries << ".");
      }
#endif // HAVE_TPETRA_DEBUG

      // Allocate the array of packed column indices.
      ind_d = lclinds_1d_type ("Tpetra::CrsGraph::ind", lclTotalNumEntries);
      // Pack the column indices.  We have to do this sequentially on
      // host, since lclInds2D_ is an ArrayRCP<Array<LO>>, which
      // doesn't work in parallel kernels (its iterators aren't even
      // thread safe in debug mode).
      {
        auto ptr_h = create_mirror_view (ptr_d);
        Kokkos::deep_copy (ptr_h, ptr_d); // we need the entries on host
        auto ind_h = create_mirror_view (ind_d); // we'll fill this on host

        // k_numRowEntries_ is a host View already, so we can use it here.
        typename row_entries_type::const_type numRowEnt_h = k_numRowEntries_;
        for (size_t row = 0; row < lclNumRows; ++row) {
          const size_t numEnt = numRowEnt_h(row);
          std::copy (lclInds2D_[row].begin (),
                     lclInds2D_[row].begin () + numEnt,
                     ind_h.ptr_on_device () + ptr_h(row));
        }
        Kokkos::deep_copy (ind_d, ind_h);
      }

#ifdef HAVE_TPETRA_DEBUG
      // Sanity check of packed row offsets.
      if (ptr_d.dimension_0 () != 0) {
        const size_t numOffsets = static_cast<size_t> (ptr_d.dimension_0 ());

        // mfh 26 Jun 2016: Don't assume UVM.  ptr_d lives in device
        // memory, so if we want to check its last entry on host, copy
        // it back to host explicitly.
        auto ptr_d_ent_d = Kokkos::subview (ptr_d, numOffsets - 1);
        auto ptr_d_ent_h = create_mirror_view (ptr_d_ent_d);
        Kokkos::deep_copy (ptr_d_ent_h, ptr_d_ent_d);
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (static_cast<size_t> (ptr_d_ent_h ()) != ind_d.dimension_0 (),
           std::logic_error, "(DynamicProfile branch) After packing column "
           "indices, ptr_d(" << (numOffsets-1) << ") = " << ptr_d_ent_h ()
           << " != ind_d.dimension_0() = " << ind_d.dimension_0 () << ".");
      }
#endif // HAVE_TPETRA_DEBUG
    }
    else if (getProfileType () == StaticProfile) {
      // StaticProfile means that the graph's column indices are
      // currently stored in a 1-D format, with row offsets in
      // k_rowPtrs_ and local column indices in k_lclInds1D_.

#ifdef HAVE_TPETRA_DEBUG
      // StaticProfile also means that the graph's array of row
      // offsets must already be allocated.
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
        (k_rowPtrs_.dimension_0 () == 0, std::logic_error,
         "(StaticProfile branch) k_rowPtrs_ has size zero, but shouldn't");
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
        (k_rowPtrs_.dimension_0 () != lclNumRows + 1, std::logic_error,
         "(StaticProfile branch) k_rowPtrs_.dimension_0() = "
         << k_rowPtrs_.dimension_0 () << " != (lclNumRows + 1) = "
         << (lclNumRows + 1) << ".");
      {
        const size_t numOffsets = k_rowPtrs_.dimension_0 ();

        // mfh 26 Jun 2016: Don't assume UVM.  k_rowPtrs_ lives in
        // device memory, so if we want to check its last entry on
        // host, copy it back to host explicitly.
        auto k_rowPtrs_ent_d = Kokkos::subview (k_rowPtrs_, numOffsets - 1);
        auto k_rowPtrs_ent_h = create_mirror_view (k_rowPtrs_ent_d);
        Kokkos::deep_copy (k_rowPtrs_ent_h, k_rowPtrs_ent_d);

        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (numOffsets != 0 &&
           k_lclInds1D_.dimension_0 () != k_rowPtrs_ent_h (),
           std::logic_error, "(StaticProfile branch) numOffsets = " <<
           numOffsets << " != 0 and k_lclInds1D_.dimension_0() = " <<
           k_lclInds1D_.dimension_0 () << " != k_rowPtrs_(" << numOffsets <<
           ") = " << k_rowPtrs_ent_h () << ".");
      }
#endif // HAVE_TPETRA_DEBUG

      if (nodeNumEntries_ != nodeNumAllocated_) {
        // The graph'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 in each row, but didn't fill
        // all those entries.

#ifdef HAVE_TPETRA_DEBUG
        if (k_rowPtrs_.dimension_0 () != 0) {
          const size_t numOffsets =
            static_cast<size_t> (k_rowPtrs_.dimension_0 ());
          // mfh 26 Jun 2016: Don't assume UVM.  k_rowPtrs_ lives in
          // device memory, so if we want to check its last entry on
          // host, copy it back to host explicitly.
          auto k_rowPtrs_ent_d = Kokkos::subview (k_rowPtrs_, numOffsets - 1);
          auto k_rowPtrs_ent_h = create_mirror_view (k_rowPtrs_ent_d);
          Kokkos::deep_copy (k_rowPtrs_ent_h, k_rowPtrs_ent_d);
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (k_rowPtrs_ent_h () != static_cast<size_t> (k_lclInds1D_.dimension_0 ()),
             std::logic_error, "(StaticProfile unpacked branch) Before "
             "allocating or packing, k_rowPtrs_(" << (numOffsets-1) << ") = "
             << k_rowPtrs_ent_h () << " != k_lclInds1D_.dimension_0() = "
             << k_lclInds1D_.dimension_0 () << ".");
        }
#endif // HAVE_TPETRA_DEBUG

        // Pack the row offsets into ptr_d, by doing a sum-scan of the
        // array of valid entry counts per row (k_numRowEntries_).

        // 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;
        {
          // Allocate the packed row offsets array.
          ptr_d = non_const_row_map_type ("Tpetra::CrsGraph::ptr", lclNumRows + 1);
          ptr_d_const = ptr_d;

          // It's ok that k_numRowEntries_ is a host View; the
          // function can handle this.
          typename row_entries_type::const_type numRowEnt_h = k_numRowEntries_;
#ifdef HAVE_TPETRA_DEBUG
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (numRowEnt_h.dimension_0 ()) != lclNumRows,
             std::logic_error, "(StaticProfile unpacked branch) "
             "numRowEnt_h.dimension_0() = " << numRowEnt_h.dimension_0 ()
             << " != getNodeNumRows() = " << lclNumRows << "");
#endif // HAVE_TPETRA_DEBUG

          lclTotalNumEntries = computeOffsetsFromCounts (ptr_d, numRowEnt_h);

#ifdef HAVE_TPETRA_DEBUG
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (ptr_d.dimension_0 ()) != lclNumRows + 1,
             std::logic_error, "(StaticProfile unpacked branch) After "
             "allocating ptr_d, ptr_d.dimension_0() = " << ptr_d.dimension_0 ()
             << " != lclNumRows+1 = " << (lclNumRows+1) << ".");
          {
            // mfh 26 Jun 2016: Don't assume UVM.  ptr_d lives in device
            // memory, so if we want to check its last entry on host, copy
            // it back to host explicitly.
            auto ptr_d_ent_d = Kokkos::subview (ptr_d, lclNumRows);
            auto ptr_d_ent_h = create_mirror_view (ptr_d_ent_d);
            Kokkos::deep_copy (ptr_d_ent_h, ptr_d_ent_d);
            TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
              (ptr_d_ent_h () != lclTotalNumEntries, std::logic_error,
               "Tpetra::CrsGraph::fillLocalGraph: In StaticProfile unpacked "
               "branch, after filling ptr_d, ptr_d(lclNumRows=" << lclNumRows
               << ") = " << ptr_d_ent_h () << " != total number of entries on "
               "the calling process = " << lclTotalNumEntries << ".");
          }
#endif // HAVE_TPETRA_DEBUG
        }

        // Allocate the array of packed column indices.
        ind_d = lclinds_1d_type ("Tpetra::CrsGraph::ind", lclTotalNumEntries);

        // k_rowPtrs_ and k_lclInds1D_ are currently unpacked.  Pack
        // them, using the packed row offsets array ptr_d that we
        // created above.
        //
        // FIXME (mfh 08 Aug 2014) If "Optimize Storage" is false (in
        // CrsMatrix?), we need to keep around the unpacked row
        // offsets and column indices.

        // Pack the column indices from unpacked k_lclInds1D_ into
        // packed ind_d.  We will replace k_lclInds1D_ below.
        typedef pack_functor<
          typename local_graph_type::entries_type::non_const_type,
          row_map_type> inds_packer_type;
        inds_packer_type f (ind_d, k_lclInds1D_, ptr_d, k_rowPtrs_);
        Kokkos::parallel_for (lclNumRows, f);

#ifdef HAVE_TPETRA_DEBUG
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (ptr_d.dimension_0 () == 0, std::logic_error, "(StaticProfile "
           "\"Optimize Storage\"=true branch) After packing, "
           "ptr_d.dimension_0() = 0.  This probably means k_rowPtrs_ was "
           "never allocated.");
        if (ptr_d.dimension_0 () != 0) {
          const size_t numOffsets = static_cast<size_t> (ptr_d.dimension_0 ());
          // mfh 26 Jun 2016: Don't assume UVM.  ptr_d lives in device
          // memory, so if we want to check its last entry on host, copy
          // it back to host explicitly.
          auto ptr_d_ent_d = Kokkos::subview (ptr_d, numOffsets - 1);
          auto ptr_d_ent_h = create_mirror_view (ptr_d_ent_d);
          Kokkos::deep_copy (ptr_d_ent_h, ptr_d_ent_d);
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (ptr_d_ent_h ()) != ind_d.dimension_0 (),
             std::logic_error, "(StaticProfile \"Optimize Storage\"=true "
             "branch) After packing, ptr_d(" << (numOffsets-1) << ") = " <<
             ptr_d_ent_h () << " != ind_d.dimension_0() = " <<
             ind_d.dimension_0 () << ".");
        }
#endif // HAVE_TPETRA_DEBUG
      }
      else { // We don't have to pack, so just set the pointers.
        ptr_d_const = k_rowPtrs_;
        ind_d = k_lclInds1D_;

#ifdef HAVE_TPETRA_DEBUG
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (ptr_d_const.dimension_0 () == 0, std::logic_error, "(StaticProfile "
           "\"Optimize Storage\"=false branch) ptr_d_const.dimension_0() = 0.  "
           "This probably means that k_rowPtrs_ was never allocated.");
        if (ptr_d_const.dimension_0 () != 0) {
          const size_t numOffsets =
            static_cast<size_t> (ptr_d_const.dimension_0 ());
          // mfh 26 Jun 2016: Don't assume UVM.  ptr_d_const lives in
          // device memory, so if we want to check its last entry on
          // host, copy it back to host explicitly.
          auto ptr_d_const_ent_d = Kokkos::subview (ptr_d_const, numOffsets - 1);
          auto ptr_d_const_ent_h = create_mirror_view (ptr_d_const_ent_d);
          Kokkos::deep_copy (ptr_d_const_ent_h, ptr_d_const_ent_d);
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (static_cast<size_t> (ptr_d_const_ent_h ()) != ind_d.dimension_0 (),
             std::logic_error, "(StaticProfile \"Optimize Storage\"=false "
             "branch) ptr_d_const(" << (numOffsets-1) << ") = " <<
             ptr_d_const_ent_h () << " != ind_d.dimension_0() = " <<
             ind_d.dimension_0 () << ".");
        }
#endif // HAVE_TPETRA_DEBUG
      }
    }

#ifdef HAVE_TPETRA_DEBUG
    // Extra sanity checks.
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (static_cast<size_t> (ptr_d_const.dimension_0 ()) != lclNumRows + 1,
       std::logic_error, "After packing, ptr_d_const.dimension_0() = " <<
       ptr_d_const.dimension_0 () << " != lclNumRows+1 = " << (lclNumRows+1)
       << ".");
    if (ptr_d_const.dimension_0 () != 0) {
      const size_t numOffsets = static_cast<size_t> (ptr_d_const.dimension_0 ());
      // mfh 26 Jun 2016: Don't assume UVM.  ptr_d_const lives in
      // device memory, so if we want to check its last entry on
      // host, copy it back to host explicitly.
      auto ptr_d_const_ent_d = Kokkos::subview (ptr_d_const, numOffsets - 1);
      auto ptr_d_const_ent_h = create_mirror_view (ptr_d_const_ent_d);
      Kokkos::deep_copy (ptr_d_const_ent_h, ptr_d_const_ent_d);
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
        (static_cast<size_t> (ptr_d_const_ent_h ()) != ind_d.dimension_0 (),
         std::logic_error, "After packing, ptr_d_const(" << (numOffsets-1) <<
         ") = " << ptr_d_const_ent_h () << " != ind_d.dimension_0() = " <<
         ind_d.dimension_0 () << ".");
    }
#endif // HAVE_TPETRA_DEBUG

    if (requestOptimizedStorage) {
      // With optimized storage, we don't need to store the 2-D column
      // indices array-of-arrays, or the array of row entry counts.

      // Free graph data structures that are only needed for 2-D or
      // unpacked 1-D storage.
      lclInds2D_ = Teuchos::null;
      k_numRowEntries_ = row_entries_type ();

      // Keep the new 1-D packed allocations.
      k_rowPtrs_   = ptr_d_const;
      k_lclInds1D_ = ind_d;

      // Storage is packed now, so the number of allocated entries is
      // the same as the actual number of entries.
      nodeNumAllocated_ = nodeNumEntries_;
      // The graph is definitely StaticProfile now, whether or not it
      // was before.
      pftype_ = StaticProfile;
    }

    // FIXME (mfh 28 Aug 2014) "Local Graph" sublist no longer used.

    // Build the local graph.
    lclGraph_ = local_graph_type (ind_d, ptr_d_const);

    // TODO (mfh 13 Mar 2014) getNodeNumDiags(), isUpperTriangular(),
    // and isLowerTriangular() depend on computeGlobalConstants(), in
    // particular the part where it looks at the local matrix.  You
    // have to use global indices to determine which entries are
    // diagonal, or above or below the diagonal.  However, lower or
    // upper triangularness is a local property.
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  replaceColMap (const Teuchos::RCP<const map_type>& newColMap)
  {
    // NOTE: This safety check matches the code, but not the documentation of Crsgraph
    //
    // FIXME (mfh 18 Aug 2014) This will break if the calling process
    // has no entries, because in that case, currently it is neither
    // locally nor globally indexed.  This will change once we get rid
    // of lazy allocation (so that the constructor allocates indices
    // and therefore commits to local vs. global).
    const char tfecfFuncName[] = "replaceColMap: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isLocallyIndexed () || isGloballyIndexed (), std::runtime_error,
      "Requires matching maps and non-static graph.");
    colMap_ = newColMap;
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  reindexColumns (const Teuchos::RCP<const map_type>& newColMap,
                  const Teuchos::RCP<const import_type>& newImport,
                  const bool sortIndicesInEachRow)
  {
    using Teuchos::REDUCE_MIN;
    using Teuchos::reduceAll;
    using Teuchos::RCP;
    typedef GlobalOrdinal GO;
    typedef LocalOrdinal LO;
    typedef typename local_graph_type::entries_type::non_const_type col_inds_type;
    const char tfecfFuncName[] = "reindexColumns: ";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillComplete (), std::runtime_error, "The graph is fill complete "
      "(isFillComplete() returns true).  You must call resumeFill() before "
      "you may call this method.");

    // mfh 19 Aug 2014: This method does NOT redistribute data; it
    // doesn't claim to do the work of an Import or Export.  This
    // means that for all processes, the calling process MUST own all
    // column indices, in both the old column Map (if it exists) and
    // the new column Map.  We check this via an all-reduce.
    //
    // Some processes may be globally indexed, others may be locally
    // indexed, and others (that have no graph entries) may be
    // neither.  This method will NOT change the graph's current
    // state.  If it's locally indexed, it will stay that way, and
    // vice versa.  It would easy to add an option to convert indices
    // from global to local, so as to save a global-to-local
    // conversion pass.  However, we don't do this here.  The intended
    // typical use case is that the graph already has a column Map and
    // is locally indexed, and this is the case for which we optimize.

    const LO lclNumRows = static_cast<LO> (this->getNodeNumRows ());

    // Attempt to convert indices to the new column Map's version of
    // local.  This will fail if on the calling process, the graph has
    // indices that are not on that process in the new column Map.
    // After the local conversion attempt, we will do an all-reduce to
    // see if any processes failed.

    // If this is false, then either the graph contains a column index
    // which is invalid in the CURRENT column Map, or the graph is
    // locally indexed but currently has no column Map.  In either
    // case, there is no way to convert the current local indices into
    // global indices, so that we can convert them into the new column
    // Map's local indices.  It's possible for this to be true on some
    // processes but not others, due to replaceColMap.
    bool allCurColIndsValid = true;
    // On the calling process, are all valid current column indices
    // also in the new column Map on the calling process?  In other
    // words, does local reindexing suffice, or should the user have
    // done an Import or Export instead?
    bool localSuffices = true;

    // Final arrays for the local indices.  We will allocate exactly
    // one of these ONLY if the graph is locally indexed on the
    // calling process, and ONLY if the graph has one or more entries
    // (is not empty) on the calling process.  In that case, we
    // allocate the first (1-D storage) if the graph has a static
    // profile, else we allocate the second (2-D storage).
    typename local_graph_type::entries_type::non_const_type newLclInds1D;
    Teuchos::ArrayRCP<Teuchos::Array<LO> > newLclInds2D;

    // If indices aren't allocated, that means the calling process
    // owns no entries in the graph.  Thus, there is nothing to
    // convert, and it trivially succeeds locally.
    if (indicesAreAllocated ()) {
      if (isLocallyIndexed ()) {
        if (hasColMap ()) { // locally indexed, and currently has a column Map
          const map_type& oldColMap = * (getColMap ());
          if (pftype_ == StaticProfile) {
            // Allocate storage for the new local indices.
            RCP<node_type> node = getRowMap ()->getNode ();
            newLclInds1D =
              col_inds_type ("Tpetra::CrsGraph::ind", nodeNumAllocated_);
            // Attempt to convert the new indices locally.
            for (LO lclRow = 0; lclRow < lclNumRows; ++lclRow) {
              const RowInfo rowInfo = this->getRowInfo (lclRow);
              const size_t beg = rowInfo.offset1D;
              const size_t end = beg + rowInfo.numEntries;
              for (size_t k = beg; k < end; ++k) {
                // FIXME (mfh 21 Aug 2014) This assumes UVM.  Should
                // use a DualView instead.
                const LO oldLclCol = k_lclInds1D_(k);
                if (oldLclCol == Teuchos::OrdinalTraits<LO>::invalid ()) {
                  allCurColIndsValid = false;
                  break; // Stop at the first invalid index
                }
                const GO gblCol = oldColMap.getGlobalElement (oldLclCol);

                // The above conversion MUST succeed.  Otherwise, the
                // current local index is invalid, which means that
                // the graph was constructed incorrectly.
                if (gblCol == Teuchos::OrdinalTraits<GO>::invalid ()) {
                  allCurColIndsValid = false;
                  break; // Stop at the first invalid index
                }
                else {
                  const LO newLclCol = newColMap->getLocalElement (gblCol);
                  if (newLclCol == Teuchos::OrdinalTraits<LO>::invalid ()) {
                    localSuffices = false;
                    break; // Stop at the first invalid index
                  }
                  // FIXME (mfh 21 Aug 2014) This assumes UVM.  Should
                  // use a DualView instead.
                  newLclInds1D(k) = newLclCol;
                }
              } // for each entry in the current row
            } // for each locally owned row
          }
          else { // pftype_ == DynamicProfile
            // Allocate storage for the new local indices.  We only
            // allocate the outer array here; we will allocate the
            // inner arrays below.
            newLclInds2D = Teuchos::arcp<Teuchos::Array<LO> > (lclNumRows);

            // Attempt to convert the new indices locally.
            for (LO lclRow = 0; lclRow < lclNumRows; ++lclRow) {
              const RowInfo rowInfo = this->getRowInfo (lclRow);
              newLclInds2D.resize (rowInfo.allocSize);

              Teuchos::ArrayView<const LO> oldLclRowView = getLocalView (rowInfo);
              Teuchos::ArrayView<LO> newLclRowView = (newLclInds2D[lclRow]) ();

              for (size_t k = 0; k < rowInfo.numEntries; ++k) {
                const LO oldLclCol = oldLclRowView[k];
                if (oldLclCol == Teuchos::OrdinalTraits<LO>::invalid ()) {
                  allCurColIndsValid = false;
                  break; // Stop at the first invalid index
                }
                const GO gblCol = oldColMap.getGlobalElement (oldLclCol);

                // The above conversion MUST succeed.  Otherwise, the
                // local index is invalid and the graph is wrong.
                if (gblCol == Teuchos::OrdinalTraits<GO>::invalid ()) {
                  allCurColIndsValid = false;
                  break; // Stop at the first invalid index
                }
                else {
                  const LO newLclCol = newColMap->getLocalElement (gblCol);
                  if (newLclCol == Teuchos::OrdinalTraits<LO>::invalid ()) {
                    localSuffices = false;
                    break; // Stop at the first invalid index.
                  }
                  newLclRowView[k] = newLclCol;
                }
              } // for each entry in the current row
            } // for each locally owned row
          } // pftype_
        }
        else { // locally indexed, but no column Map
          // This case is only possible if replaceColMap() was called
          // with a null argument on the calling process.  It's
          // possible, but it means that this method can't possibly
          // succeed, since we have no way of knowing how to convert
          // the current local indices to global indices.
          allCurColIndsValid = false;
        }
      }
      else { // globally indexed
        // If the graph is globally indexed, we don't need to save
        // local indices, but we _do_ need to know whether the current
        // global indices are valid in the new column Map.  We may
        // need to do a getRemoteIndexList call to find this out.
        //
        // In this case, it doesn't matter whether the graph currently
        // has a column Map.  We don't need the old column Map to
        // convert from global indices to the _new_ column Map's local
        // indices.  Furthermore, we can use the same code, whether
        // the graph is static or dynamic profile.

        // Test whether the current global indices are in the new
        // column Map on the calling process.
        for (LO lclRow = 0; lclRow < lclNumRows; ++lclRow) {
          const RowInfo rowInfo = this->getRowInfo (lclRow);
          Teuchos::ArrayView<const GO> oldGblRowView = getGlobalView (rowInfo);
          for (size_t k = 0; k < rowInfo.numEntries; ++k) {
            const GO gblCol = oldGblRowView[k];
            if (! newColMap->isNodeGlobalElement (gblCol)) {
              localSuffices = false;
              break; // Stop at the first invalid index
            }
          } // for each entry in the current row
        } // for each locally owned row
      } // locally or globally indexed
    } // whether indices are allocated

    // Do an all-reduce to check both possible error conditions.
    int lclSuccess[2];
    lclSuccess[0] = allCurColIndsValid ? 1 : 0;
    lclSuccess[1] = localSuffices ? 1 : 0;
    int gblSuccess[2];
    gblSuccess[0] = 0;
    gblSuccess[1] = 0;
    RCP<const Teuchos::Comm<int> > comm =
      getRowMap ().is_null () ? Teuchos::null : getRowMap ()->getComm ();
    if (! comm.is_null ()) {
      reduceAll<int, int> (*comm, REDUCE_MIN, 2, lclSuccess, gblSuccess);
    }

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      gblSuccess[0] == 0, std::runtime_error, "It is not possible to continue."
      "  The most likely reason is that the graph is locally indexed, but the "
      "column Map is missing (null) on some processes, due to a previous call "
      "to replaceColMap().");

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      gblSuccess[1] == 0, std::runtime_error, "On some process, the graph "
      "contains column indices that are in the old column Map, but not in the "
      "new column Map (on that process).  This method does NOT redistribute "
      "data; it does not claim to do the work of an Import or Export operation."
      "  This means that for all processess, the calling process MUST own all "
      "column indices, in both the old column Map and the new column Map.  In "
      "this case, you will need to do an Import or Export operation to "
      "redistribute data.");

    // Commit the results.
    if (isLocallyIndexed ()) {
      if (pftype_ == StaticProfile) {
        k_lclInds1D_ = newLclInds1D;
      } else { // dynamic profile
        lclInds2D_ = newLclInds2D;
      }
      // We've reindexed, so we don't know if the indices are sorted.
      //
      // FIXME (mfh 17 Sep 2014) It could make sense to check this,
      // since we're already going through all the indices above.  We
      // could also sort each row in place; that way, we would only
      // have to make one pass over the rows.
      indicesAreSorted_ = false;
      if (sortIndicesInEachRow) {
        // NOTE (mfh 17 Sep 2014) The graph must be locally indexed in
        // order to call this method.
        //
        // FIXME (mfh 17 Sep 2014) This violates the strong exception
        // guarantee.  It would be better to sort the new index arrays
        // before committing them.
        sortAllIndices ();
      }
    }
    colMap_ = newColMap;

    if (newImport.is_null ()) {
      // FIXME (mfh 19 Aug 2014) Should use the above all-reduce to
      // check whether the input Import is null on any process.
      //
      // If the domain Map hasn't been set yet, we can't compute a new
      // Import object.  Leave it what it is; it should be null, but
      // it doesn't matter.  If the domain Map _has_ been set, then
      // compute a new Import object if necessary.
      if (! domainMap_.is_null ()) {
        if (! domainMap_->isSameAs (* newColMap)) {
          importer_ = Teuchos::rcp (new import_type (domainMap_, newColMap));
        } else {
          importer_ = Teuchos::null; // don't need an Import
        }
      }
    } else {
      // The caller gave us an Import object.  Assume that it's valid.
      importer_ = newImport;
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  replaceDomainMapAndImporter (const Teuchos::RCP<const map_type>& newDomainMap,
                               const Teuchos::RCP<const import_type>& newImporter)
  {
    const char prefix[] = "Tpetra::CrsGraph::replaceDomainMapAndImporter: ";
    TEUCHOS_TEST_FOR_EXCEPTION(
      colMap_.is_null (), std::invalid_argument, prefix << "You may not call "
      "this method unless the graph already has a column Map.");
    TEUCHOS_TEST_FOR_EXCEPTION(
      newDomainMap.is_null (), std::invalid_argument,
      prefix << "The new domain Map must be nonnull.");

#ifdef HAVE_TPETRA_DEBUG
    if (newImporter.is_null ()) {
      // It's not a good idea to put expensive operations in a macro
      // clause, even if they are side effect - free, because macros
      // don't promise that they won't evaluate their arguments more
      // than once.  It's polite for them to do so, but not required.
      const bool colSameAsDom = colMap_->isSameAs (*newDomainMap);
      TEUCHOS_TEST_FOR_EXCEPTION(
        colSameAsDom, std::invalid_argument, "If the new Import is null, "
        "then the new domain Map must be the same as the current column Map.");
    }
    else {
      const bool colSameAsTgt =
        colMap_->isSameAs (* (newImporter->getTargetMap ()));
      const bool newDomSameAsSrc =
        newDomainMap->isSameAs (* (newImporter->getSourceMap ()));
      TEUCHOS_TEST_FOR_EXCEPTION(
        ! colSameAsTgt || ! newDomSameAsSrc, std::invalid_argument, "If the "
        "new Import is nonnull, then the current column Map must be the same "
        "as the new Import's target Map, and the new domain Map must be the "
        "same as the new Import's source Map.");
    }
#endif // HAVE_TPETRA_DEBUG

    domainMap_ = newDomainMap;
    importer_ = Teuchos::rcp_const_cast<import_type> (newImporter);
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  typename CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::local_graph_type
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalGraph () const
  {
    return lclGraph_;
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  computeGlobalConstants ()
  {
    using Teuchos::ArrayView;
    using Teuchos::outArg;
    using Teuchos::reduceAll;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    typedef global_size_t GST;

#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(! hasColMap(), std::logic_error, "Tpetra::"
      "CrsGraph::computeGlobalConstants: At this point, the graph should have "
      "a column Map, but it does not.  Please report this bug to the Tpetra "
      "developers.");
#endif // HAVE_TPETRA_DEBUG

    // If necessary, (re)compute the local constants: nodeNumDiags_,
    // lowerTriangular_, upperTriangular_, and nodeMaxNumRowEntries_.
    if (! haveLocalConstants_) {
      // We have actually already computed nodeNumEntries_.
      // nodeNumEntries_ gets updated by methods that insert or remove
      // indices (including setAllIndices and
      // expertStaticFillComplete).  Before fillComplete, its count
      // may include duplicate column indices in the same row.
      // However, mergeRowIndices and mergeRowIndicesAndValues both
      // subtract off merged indices in each row from the total count.
      // Thus, nodeNumEntries_ _should_ be accurate at this point,
      // meaning that we don't have to re-count it here.

      // Reset local properties
      upperTriangular_ = true;
      lowerTriangular_ = true;
      nodeMaxNumRowEntries_ = 0;
      nodeNumDiags_         = 0;

      // At this point, we know that we have both a row Map and a column Map.
      const map_type& rowMap = *rowMap_;
      const map_type& colMap = *colMap_;

      // Go through all the entries of the graph.  Count the number of
      // diagonal elements we encounter, and figure out whether the
      // graph is lower or upper triangular.  Diagonal elements are
      // determined using global indices, with respect to the whole
      // graph.  However, lower or upper triangularity is a local
      // property, and is determined using local indices.
      //
      // At this point, indices have already been sorted in each row.
      // That makes finding out whether the graph is lower / upper
      // triangular easier.
      if (indicesAreAllocated () && nodeNumAllocated_ > 0) {
        const LO numLocalRows = static_cast<LO> (this->getNodeNumRows ());
        for (LO localRow = 0; localRow < numLocalRows; ++localRow) {
          const GO globalRow = rowMap.getGlobalElement (localRow);
          // Find the local (column) index for the diagonal entry.
          // This process might not necessarily own _any_ entries in
          // the current row.  If it doesn't, skip this row.  It won't
          // affect any of the attributes (nodeNumDiagons_,
          // upperTriangular_, lowerTriangular_, or
          // nodeMaxNumRowEntries_) which this loop sets.
          const LO rlcid = colMap.getLocalElement (globalRow);
            // This process owns one or more entries in the current row.
            const RowInfo rowInfo = this->getRowInfo (localRow);
            ArrayView<const LO> rview = getLocalView (rowInfo);
            typename ArrayView<const LO>::iterator beg, end, cur;
            beg = rview.begin();
            end = beg + rowInfo.numEntries;
            if (beg != end) {
              for (cur = beg; cur != end; ++cur) {
                // is this the diagonal?
                if (rlcid == *cur) ++nodeNumDiags_;
              }
              // Local column indices are sorted in each row.  That means
              // the smallest column index in this row (on this process)
              // is *beg, and the largest column index in this row (on
              // this process) is *(end - 1).  We know that end - 1 is
              // valid because beg != end.
              const size_t smallestCol = static_cast<size_t> (*beg);
              const size_t largestCol = static_cast<size_t> (*(end - 1));

              if (smallestCol < static_cast<size_t> (localRow)) {
                upperTriangular_ = false;
              }
              if (static_cast<size_t> (localRow) < largestCol) {
                lowerTriangular_ = false;
              }
            }
            // Update the max number of entries over all rows.
            nodeMaxNumRowEntries_ = std::max (nodeMaxNumRowEntries_, rowInfo.numEntries);
        }
      }
      haveLocalConstants_ = true;
    } // if my process doesn't have local constants

    // Compute global constants from local constants.  Processes that
    // already have local constants still participate in the
    // all-reduces, using their previously computed values.
    if (haveGlobalConstants_ == false) {
      // Promote all the nodeNum* and nodeMaxNum* quantities from
      // size_t to global_size_t, when doing the all-reduces for
      // globalNum* / globalMaxNum* results.
      //
      // FIXME (mfh 07 May 2013) Unfortunately, we either have to do
      // this in two all-reduces (one for the sum and the other for
      // the max), or use a custom MPI_Op that combines the sum and
      // the max.  The latter might even be slower than two
      // all-reduces on modern network hardware.  It would also be a
      // good idea to use nonblocking all-reduces (MPI 3), so that we
      // don't have to wait around for the first one to finish before
      // starting the second one.
      GST lcl[2], gbl[2];
      lcl[0] = static_cast<GST> (nodeNumEntries_);
      lcl[1] = static_cast<GST> (nodeNumDiags_);
      reduceAll<int,GST> (*getComm (), Teuchos::REDUCE_SUM,
                          2, lcl, gbl);
      globalNumEntries_ = gbl[0];
      globalNumDiags_   = gbl[1];
      reduceAll<int,GST> (*getComm (), Teuchos::REDUCE_MAX,
                          static_cast<GST> (nodeMaxNumRowEntries_),
                          outArg (globalMaxNumRowEntries_));
      haveGlobalConstants_ = true;
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  makeIndicesLocal ()
  {
    using Teuchos::arcp;
    using Teuchos::Array;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    typedef device_type DT;
    typedef typename local_graph_type::row_map_type::non_const_value_type offset_type;
    typedef decltype (k_numRowEntries_) row_entries_type;
    typedef typename row_entries_type::non_const_value_type num_ent_type;
    typedef typename local_graph_type::entries_type::non_const_type
      lcl_col_inds_type;
    typedef Kokkos::View<GO*, typename lcl_col_inds_type::array_layout,
      device_type> gbl_col_inds_type;

    const char tfecfFuncName[] = "makeIndicesLocal: ";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (! this->hasColMap (), std::logic_error, "The graph does not have a "
       "column Map yet.  This method should never be called in that case.  "
       "Please report this bug to the Tpetra developers.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (this->getColMap ().is_null (), std::logic_error, "The graph claims "
       "that it has a column Map, because hasColMap() returns true.  However, "
       "the result of getColMap() is null.  This should never happen.  Please "
       "report this bug to the Tpetra developers.");

    const LO lclNumRows = static_cast<LO> (this->getNodeNumRows ());
    const map_type& colMap = * (this->getColMap ());

    if (isGloballyIndexed () && lclNumRows != 0) {
      // This is a host View.
      typename row_entries_type::const_type h_numRowEnt = k_numRowEntries_;

      // allocate data for local indices
      if (getProfileType () == StaticProfile) {
        // If GO and LO are the same size, we can reuse the existing
        // array of 1-D index storage to convert column indices from
        // GO to LO.  Otherwise, we'll just allocate a new buffer.
        constexpr bool LO_GO_same = std::is_same<LO, GO>::value;
        if (nodeNumAllocated_ && LO_GO_same) {
          // This prevents a build error (illegal assignment) if
          // LO_GO_same is _not_ true.
          k_lclInds1D_ = Kokkos::Impl::if_c<LO_GO_same,
            t_GlobalOrdinal_1D,
            lcl_col_inds_type>::select (k_gblInds1D_, k_lclInds1D_);
        }
        else {
          TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
            (k_rowPtrs_.dimension_0 () == 0, std::logic_error,
             "k_rowPtrs_.dimension_0() == 0.  This should never happen at this "
             "point.  Please report this bug to the Tpetra developers.");

          // Don't assume UVM.  Get a ("0-D") View of the last entry
          // of k_rowPtrs_, get its host mirror View, and use that to
          // get the number of entries.
          auto lastEnt_d = Kokkos::subview (k_rowPtrs_, lclNumRows);
          auto lastEnt_h = Kokkos::create_mirror_view (lastEnt_d);
          Kokkos::deep_copy (lastEnt_h, lastEnt_d);
          const auto numEnt = lastEnt_h ();

          k_lclInds1D_ = lcl_col_inds_type ("Tpetra::CrsGraph::lclind", numEnt);
        }

        auto lclColMap = colMap.getLocalMap ();
        // This is a "device mirror" of the host View h_numRowEnt.
        //
        // NOTE (mfh 27 Sep 2016) Currently, the right way to get a
        // Device instance is to use its default constructor.  See the
        // following Kokkos issue:
        //
        // https://github.com/kokkos/kokkos/issues/442
        auto k_numRowEnt = Kokkos::create_mirror_view (device_type (), h_numRowEnt);

        using Details::convertColumnIndicesFromGlobalToLocal;
        const size_t numBad =
          convertColumnIndicesFromGlobalToLocal<LO, GO, DT, offset_type, num_ent_type> (k_lclInds1D_,
                                                                                        k_gblInds1D_,
                                                                                        k_rowPtrs_,
                                                                                        lclColMap,
                                                                                        k_numRowEnt);
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
          (numBad != 0, std::runtime_error, "When converting column indices "
           "from global to local, we encountered " << numBad
           << "ind" << (numBad != static_cast<size_t> (1) ? "ices" : "ex")
           << " that do" << (numBad != static_cast<size_t> (1) ? "es" : "")
           << " not live in the column Map on this process.");

        // We've converted column indices from global to local, so we
        // can deallocate the global column indices (which we know are
        // in 1-D storage, because the graph has static profile).
        k_gblInds1D_ = gbl_col_inds_type ();
      }
      else {  // the graph has dynamic profile (2-D index storage)
        lclInds2D_ = Teuchos::arcp<Teuchos::Array<LO> > (lclNumRows);
        for (LO lclRow = 0; lclRow < lclNumRows; ++lclRow) {
          if (! gblInds2D_[lclRow].empty ()) {
            const GO* const ginds = gblInds2D_[lclRow].getRawPtr ();
            // NOTE (mfh 26 Jun 2016) It's always legal to cast the
            // number of entries in a row to LO, as long as the row
            // doesn't have too many duplicate entries.
            const LO rna = static_cast<LO> (gblInds2D_[lclRow].size ());
            const LO numEnt = static_cast<LO> (h_numRowEnt(lclRow));
            lclInds2D_[lclRow].resize (rna);
            LO* const linds = lclInds2D_[lclRow].getRawPtr ();
            for (LO j = 0; j < numEnt; ++j) {
              const GO gid = ginds[j];
              const LO lid = colMap.getLocalElement (gid);
              linds[j] = lid;
#ifdef HAVE_TPETRA_DEBUG
              TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
                (linds[j] == Teuchos::OrdinalTraits<LO>::invalid(),
                 std::logic_error,
                 "Global column ginds[j=" << j << "]=" << ginds[j]
                 << " of local row " << lclRow << " is not in the column Map.  "
                 "This should never happen.  Please report this bug to the "
                 "Tpetra developers.");
#endif // HAVE_TPETRA_DEBUG
            }
          }
        }
        gblInds2D_ = Teuchos::null;
      }
    } // globallyIndexed() && lclNumRows > 0

    lclGraph_ = local_graph_type (k_lclInds1D_, k_rowPtrs_);
    indicesAreLocal_  = true;
    indicesAreGlobal_ = false;
    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  sortAllIndices ()
  {
    typedef LocalOrdinal LO;

    // this should be called only after makeIndicesLocal()
    TEUCHOS_TEST_FOR_EXCEPT( isGloballyIndexed () );
    if (isSorted () == false) {
      // FIXME (mfh 06 Mar 2014) This would be a good place for a
      // thread-parallel kernel.
      const LO lclNumRows = static_cast<LO> (this->getNodeNumRows ());
      for (LO lclRow = 0; lclRow < lclNumRows; ++lclRow) {
        const RowInfo rowInfo = this->getRowInfo (lclRow);
        this->sortRowIndices (rowInfo);
      }
    }
    indicesAreSorted_ = true; // we just sorted every row
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  makeColMap ()
  {
    using Teuchos::Array;
    using Teuchos::ArrayView;
    using Teuchos::outArg;
    using Teuchos::rcp;
    using Teuchos::REDUCE_MAX;
    using Teuchos::reduceAll;
    using std::endl;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    const char tfecfFuncName[] = "makeColMap";

    if (hasColMap ()) { // The graph already has a column Map.
      // FIXME (mfh 26 Feb 2013): This currently prevents structure
      // changes that affect the column Map.
      return;
    }

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isLocallyIndexed (), std::runtime_error,
      ": The graph is locally indexed.  Calling makeColMap() to make the "
      "column Map requires that the graph be globally indexed.");

    // After the calling process is done going through all of the rows
    // it owns, myColumns will contain the list of indices owned by
    // this process in the column Map.
    Array<GO> myColumns;

    // If we reach this point, we don't have a column Map yet, so the
    // graph can't be locally indexed.  Thus, isGloballyIndexed() ==
    // false means that the graph is empty on this process, so
    // myColumns will be left empty.
    if (isGloballyIndexed ()) {
      // Go through all the rows, finding the populated column indices.
      //
      // Our final list of indices for the column Map constructor will
      // have the following properties (all of which are with respect
      // to the calling process):
      //
      // 1. Indices in the domain Map go first.
      // 2. Indices not in the domain Map follow, ordered first
      //    contiguously by their owning process rank (in the domain
      //    Map), then in increasing order within that.
      // 3. No duplicate indices.
      //
      // This imitates the ordering used by Aztec(OO) and Epetra.
      // Storing indices owned by the same process (in the domain Map)
      // contiguously permits the use of contiguous send and receive
      // buffers.
      //
      // We begin by partitioning the column indices into "local" GIDs
      // (owned by the domain Map) and "remote" GIDs (not owned by the
      // domain Map).  We use the same order for local GIDs as the
      // domain Map, so we track them in place in their array.  We use
      // an std::set (RemoteGIDSet) to keep track of remote GIDs, so
      // that we don't have to merge duplicates later.
      const LO LINV = Teuchos::OrdinalTraits<LO>::invalid ();
      size_t numLocalColGIDs = 0, numRemoteColGIDs = 0;

      // GIDisLocal[lid] == 0 if and only if local index lid in the
      // domain Map is remote (not local).
      Array<char> GIDisLocal (domainMap_->getNodeNumElements (), 0);
      std::set<GO> RemoteGIDSet;
      // This preserves the not-sorted Epetra order of GIDs.
      std::vector<GO> RemoteGIDUnorderedVector;
      const LO myNumRows = this->getNodeNumRows ();
      for (LO r = 0; r < myNumRows; ++r) {
        const RowInfo rowinfo = this->getRowInfo (r);
        if (rowinfo.numEntries > 0) {
          // NOTE (mfh 02 Sep 2014) getGlobalView() returns a view of
          // all the space in the row, not just the occupied entries.
          // (This matters for the case of unpacked 1-D storage.  We
          // might not have packed it yet.)  That's why we need to
          // take a subview.
          ArrayView<const GO> rowGids = getGlobalView (rowinfo);
          rowGids = rowGids (0, rowinfo.numEntries);

          for (size_t k = 0; k < rowinfo.numEntries; ++k) {
            const GO gid = rowGids[k];
            const LO lid = domainMap_->getLocalElement (gid);
            if (lid != LINV) {
              const char alreadyFound = GIDisLocal[lid];
              if (alreadyFound == 0) {
                GIDisLocal[lid] = static_cast<char> (1);
                ++numLocalColGIDs;
              }
            }
            else {
              const bool notAlreadyFound = RemoteGIDSet.insert (gid).second;
              if (notAlreadyFound) { // gid did not exist in the set before
                if (! sortGhostsAssociatedWithEachProcessor_) {
                  // The user doesn't want to sort remote GIDs (for
                  // each remote process); they want us to keep remote
                  // GIDs in their original order.  We do this by
                  // stuffing each remote GID into an array as we
                  // encounter it for the first time.  The std::set
                  // helpfully tracks first encounters.
                  RemoteGIDUnorderedVector.push_back (gid);
                }
                ++numRemoteColGIDs;
              }
            }
          } // for each entry k in row r
        } // if row r contains > 0 entries
      } // for each locally owned row r

      // Possible short-circuit for serial scenario:
      //
      // If all domain GIDs are present as column indices, then set
      // ColMap=DomainMap.  By construction, LocalGIDs is a subset of
      // DomainGIDs.
      //
      // If we have
      //   * Number of remote GIDs is 0, so that ColGIDs == LocalGIDs,
      // and
      //   * Number of local GIDs is number of domain GIDs
      // then
      //   * LocalGIDs \subset DomainGIDs && size(LocalGIDs) ==
      //     size(DomainGIDs) => DomainGIDs == LocalGIDs == ColGIDs
      // on the calling process.
      //
      // We will concern ourselves only with the special case of a
      // serial DomainMap, obviating the need for communication.
      //
      // If
      //   * DomainMap has a serial communicator
      // then we can set the column Map as the domain Map
      // return. Benefit: this graph won't need an Import object
      // later.
      //
      // Note, for a serial domain map, there can be no RemoteGIDs,
      // because there are no remote processes.  Likely explanations
      // for this are:
      //  * user submitted erroneous column indices
      //  * user submitted erroneous domain Map
      if (domainMap_->getComm ()->getSize () == 1) {
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
          numRemoteColGIDs != 0, std::runtime_error,
          ": " << numRemoteColGIDs << " column "
          << (numRemoteColGIDs != 1 ? "indices are" : "index is")
          << " not in the domain Map." << endl
          << "Either these indices are invalid or the domain Map is invalid."
          << endl << "Remember that nonsquare matrices, or matrices where the "
          "row and range Maps are different, require calling the version of "
          "fillComplete that takes the domain and range Maps as input.");
        if (numLocalColGIDs == domainMap_->getNodeNumElements()) {
          colMap_ = domainMap_;
          checkInternalState ();
          return;
        }
      }

      // Populate myColumns with a list of all column GIDs.  Put
      // locally owned (in the domain Map) GIDs at the front: they
      // correspond to "same" and "permuted" entries between the
      // column Map and the domain Map.  Put remote GIDs at the back.
      myColumns.resize (numLocalColGIDs + numRemoteColGIDs);
      // get pointers into myColumns for each part
      ArrayView<GO> LocalColGIDs  = myColumns (0, numLocalColGIDs);
      ArrayView<GO> RemoteColGIDs = myColumns (numLocalColGIDs, numRemoteColGIDs);

      // Copy the remote GIDs into myColumns
      if (sortGhostsAssociatedWithEachProcessor_) {
        // The std::set puts GIDs in increasing order.
        std::copy (RemoteGIDSet.begin(), RemoteGIDSet.end(),
                   RemoteColGIDs.begin());
      } else {
        // Respect the originally encountered order.
        std::copy (RemoteGIDUnorderedVector.begin(),
                   RemoteGIDUnorderedVector.end(), RemoteColGIDs.begin());
      }

      // Make a list of process ranks corresponding to the remote GIDs.
      Array<int> RemoteImageIDs (numRemoteColGIDs);
      // Look up the remote process' ranks in the domain Map.
      {
        const LookupStatus stat =
          domainMap_->getRemoteIndexList (RemoteColGIDs, RemoteImageIDs ());
#ifdef HAVE_TPETRA_DEBUG
        // If any process returns IDNotPresent, then at least one of
        // the remote indices was not present in the domain Map.  This
        // means that the Import object cannot be constructed, because
        // of incongruity between the column Map and domain Map.
        // This has two likely causes:
        //   - The user has made a mistake in the column indices
        //   - The user has made a mistake with respect to the domain Map
        const int missingID_lcl = (stat == IDNotPresent ? 1 : 0);
        int missingID_gbl = 0;
        reduceAll<int, int> (*getComm (), REDUCE_MAX, missingID_lcl,
                             outArg (missingID_gbl));
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
          missingID_gbl == 1, std::runtime_error,
          ": Some column indices are not in the domain Map." << endl
          << "Either these column indices are invalid or the domain Map is "
          "invalid." << endl << "Likely cause: For a nonsquare matrix, you "
          "must give the domain and range Maps as input to fillComplete.");
#else
        (void) stat; // forestall compiler warning for unused variable
#endif // HAVE_TPETRA_DEBUG
      }
      // Sort incoming remote column indices by their owning process
      // rank, so that all columns coming from a given remote process
      // are contiguous.  This means the Import's Distributor doesn't
      // need to reorder data.
      //
      // NOTE (mfh 02 Sep 2014) This needs to be a stable sort, so
      // that it respects either of the possible orderings of GIDs
      // (sorted, or original order) specified above.
      sort2 (RemoteImageIDs.begin(), RemoteImageIDs.end(), RemoteColGIDs.begin());

      // Copy the local GIDs into myColumns. Two cases:
      // 1. If the number of Local column GIDs is the same as the
      //    number of Local domain GIDs, we can simply read the domain
      //    GIDs into the front part of ColIndices (see logic above
      //    from the serial short circuit case)
      // 2. We step through the GIDs of the DomainMap, checking to see
      //    if each domain GID is a column GID.  We want to do this to
      //    maintain a consistent ordering of GIDs between the columns
      //    and the domain.

      const size_t numDomainElts = domainMap_->getNodeNumElements ();
      if (numLocalColGIDs == numDomainElts) {
        // If the number of locally owned GIDs are the same as the
        // number of local domain Map elements, then the local domain
        // Map elements are the same as the locally owned GIDs.
        if (domainMap_->isContiguous ()) {
          // NOTE (mfh 03 Mar 2013, 02 Sep 2014) In the common case
          // that the domain Map is contiguous, it's more efficient to
          // avoid calling getNodeElementList(), since that
          // permanently constructs and caches the GID list in the
          // contiguous Map.
          GO curColMapGid = domainMap_->getMinGlobalIndex ();
          for (size_t k = 0; k < numLocalColGIDs; ++k, ++curColMapGid) {
            LocalColGIDs[k] = curColMapGid;
          }
        }
        else {
          ArrayView<const GO> domainElts = domainMap_->getNodeElementList ();
          std::copy (domainElts.begin(), domainElts.end(), LocalColGIDs.begin());
        }
      }
      else {
        // Count the number of locally owned GIDs, both to keep track
        // of the current array index, and as a sanity check.
        size_t numLocalCount = 0;
        if (domainMap_->isContiguous ()) {
          // NOTE (mfh 03 Mar 2013, 02 Sep 2014) In the common case
          // that the domain Map is contiguous, it's more efficient to
          // avoid calling getNodeElementList(), since that
          // permanently constructs and caches the GID list in the
          // contiguous Map.
          GO curColMapGid = domainMap_->getMinGlobalIndex ();
          for (size_t i = 0; i < numDomainElts; ++i, ++curColMapGid) {
            if (GIDisLocal[i]) {
              LocalColGIDs[numLocalCount++] = curColMapGid;
            }
          }
        }
        else {
          ArrayView<const GO> domainElts = domainMap_->getNodeElementList ();
          for (size_t i = 0; i < numDomainElts; ++i) {
            if (GIDisLocal[i]) {
              LocalColGIDs[numLocalCount++] = domainElts[i];
            }
          }
        }
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
          numLocalCount != numLocalColGIDs, std::logic_error,
          ": numLocalCount = " << numLocalCount << " != numLocalColGIDs = "
          << numLocalColGIDs << ".  This should never happen.  Please report "
          "this bug to the Tpetra developers.");
      }

      // FIXME (mfh 03 Apr 2013) Now would be a good time to use the
      // information we collected above to construct the Import.  In
      // particular, building an Import requires:
      //
      // 1. numSameIDs (length of initial contiguous sequence of GIDs
      //    on this process that are the same in both Maps; this
      //    equals the number of domain Map elements on this process)
      //
      // 2. permuteToLIDs and permuteFromLIDs (both empty in this
      //    case, since there's no permutation going on; the column
      //    Map starts with the domain Map's GIDs, and immediately
      //    after them come the remote GIDs)
      //
      // 3. remoteGIDs (exactly those GIDs that we found out above
      //    were not in the domain Map) and remoteLIDs (which we could
      //    have gotten above by using the three-argument version of
      //    getRemoteIndexList() that computes local indices as well
      //    as process ranks, instead of the two-argument version that
      //    was used above)
      //
      // 4. remotePIDs (which we have from the getRemoteIndexList()
      //    call above)
      //
      // 5. Sorting remotePIDs, and applying that permutation to
      //    remoteGIDs and remoteLIDs (by calling sort3 above instead
      //    of sort2)
      //
      // 6. Everything after the sort3 call in Import::setupExport():
      //    a. Create the Distributor via createFromRecvs(), which
      //       computes exportGIDs and exportPIDs
      //    b. Compute exportLIDs from exportGIDs (by asking the
      //       source Map, in this case the domain Map, to convert
      //       global to local)
      //
      // Steps 1-5 come for free, since we must do that work anyway in
      // order to compute the column Map.  In particular, Step 3 is
      // even more expensive than Step 6a, since it involves both
      // creating and using a new Distributor object.

    } // if the graph is globally indexed

    const global_size_t gstInv =
      Teuchos::OrdinalTraits<global_size_t>::invalid ();
    // FIXME (mfh 05 Mar 2014) Doesn't the index base of a Map have to
    // be the same as the Map's min GID? If the first column is empty
    // (contains no entries), then the column Map's min GID won't
    // necessarily be the same as the domain Map's index base.
    const GO indexBase = domainMap_->getIndexBase ();
    colMap_ = rcp (new map_type (gstInv, myColumns, indexBase,
                                 domainMap_->getComm (),
                                 domainMap_->getNode ()));

    checkInternalState ();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  mergeAllIndices ()
  {
    TEUCHOS_TEST_FOR_EXCEPT( isGloballyIndexed() ); // call only after makeIndicesLocal()
    TEUCHOS_TEST_FOR_EXCEPT( ! isSorted() ); // call only after sortIndices()
    if (! isMerged ()) {
      const LocalOrdinal lclNumRows =
        static_cast<LocalOrdinal> (this->getNodeNumRows ());
      for (LocalOrdinal row = 0; row < lclNumRows; ++row) {
        const RowInfo rowInfo = this->getRowInfo (row);
        mergeRowIndices(rowInfo);
      }
      // we just merged every row
      noRedundancies_ = true;
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  makeImportExport ()
  {
    using Teuchos::ParameterList;
    using Teuchos::RCP;
    using Teuchos::rcp;

    TEUCHOS_TEST_FOR_EXCEPTION(! hasColMap (), std::logic_error, "Tpetra::"
      "CrsGraph::makeImportExport: This method may not be called unless the "
      "graph has a column Map.");
    RCP<ParameterList> params = this->getNonconstParameterList (); // could be null

    // Don't do any checks to see if we need to create the Import, if
    // it exists already.
    //
    // FIXME (mfh 25 Mar 2013) This will become incorrect if we
    // change CrsGraph in the future to allow changing the column
    // Map after fillComplete.  For now, the column Map is fixed
    // after the first fillComplete call.
    if (importer_.is_null ()) {
      // Create the Import instance if necessary.
      if (domainMap_ != colMap_ && (! domainMap_->isSameAs (*colMap_))) {
        if (params.is_null () || ! params->isSublist ("Import")) {
          importer_ = rcp (new import_type (domainMap_, colMap_));
        } else {
          RCP<ParameterList> importSublist = sublist (params, "Import", true);
          importer_ = rcp (new import_type (domainMap_, colMap_, importSublist));
        }
      }
    }

    // Don't do any checks to see if we need to create the Export, if
    // it exists already.
    if (exporter_.is_null ()) {
      // Create the Export instance if necessary.
      if (rangeMap_ != rowMap_ && ! rangeMap_->isSameAs (*rowMap_)) {
        if (params.is_null () || ! params->isSublist ("Export")) {
          exporter_ = rcp (new export_type (rowMap_, rangeMap_));
        }
        else {
          RCP<ParameterList> exportSublist = sublist (params, "Export", true);
          exporter_ = rcp (new export_type (rowMap_, rangeMap_, exportSublist));
        }
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  std::string
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  description () const
  {
    std::ostringstream oss;
    oss << dist_object_type::description ();
    if (isFillComplete ()) {
      oss << "{status = fill complete"
          << ", global rows = " << getGlobalNumRows()
          << ", global cols = " << getGlobalNumCols()
          << ", global num entries = " << getGlobalNumEntries()
          << "}";
    }
    else {
      oss << "{status = fill not complete"
          << ", global rows = " << getGlobalNumRows()
          << "}";
    }
    return oss.str();
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  describe (Teuchos::FancyOStream &out,
            const Teuchos::EVerbosityLevel verbLevel) const
  {
    const char tfecfFuncName[] = "describe()";
    using Teuchos::ArrayView;
    using Teuchos::Comm;
    using Teuchos::RCP;
    using Teuchos::VERB_DEFAULT;
    using Teuchos::VERB_NONE;
    using Teuchos::VERB_LOW;
    using Teuchos::VERB_MEDIUM;
    using Teuchos::VERB_HIGH;
    using Teuchos::VERB_EXTREME;
    using std::endl;
    using std::setw;

    Teuchos::EVerbosityLevel vl = verbLevel;
    if (vl == VERB_DEFAULT) vl = VERB_LOW;
    RCP<const Comm<int> > comm = this->getComm();
    const int myImageID = comm->getRank(),
              numImages = 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;
    Teuchos::OSTab tab (out);
    //    none: print nothing
    //     low: print O(1) info from node 0
    //  medium: print O(P) info, num entries per node
    //    high: print O(N) info, num entries per row
    // extreme: print O(NNZ) info: print graph indices
    //
    // for medium and higher, print constituent objects at specified verbLevel
    if (vl != VERB_NONE) {
      if (myImageID == 0) out << this->description() << std::endl;
      // O(1) globals, minus what was already printed by description()
      if (isFillComplete() && myImageID == 0) {
        out << "Global number of diagonals = " << globalNumDiags_ << std::endl;
        out << "Global max number of row entries = " << globalMaxNumRowEntries_ << std::endl;
      }
      // constituent objects
      if (vl == VERB_MEDIUM || vl == VERB_HIGH || vl == VERB_EXTREME) {
        if (myImageID == 0) out << "\nRow map: " << std::endl;
        rowMap_->describe(out,vl);
        if (colMap_ != Teuchos::null) {
          if (myImageID == 0) out << "\nColumn map: " << std::endl;
          colMap_->describe(out,vl);
        }
        if (domainMap_ != Teuchos::null) {
          if (myImageID == 0) out << "\nDomain map: " << std::endl;
          domainMap_->describe(out,vl);
        }
        if (rangeMap_ != Teuchos::null) {
          if (myImageID == 0) out << "\nRange map: " << std::endl;
          rangeMap_->describe(out,vl);
        }
      }
      // O(P) data
      if (vl == VERB_MEDIUM || vl == VERB_HIGH || vl == VERB_EXTREME) {
        for (int imageCtr = 0; imageCtr < numImages; ++imageCtr) {
          if (myImageID == imageCtr) {
            out << "Node ID = " << imageCtr << std::endl
                << "Node number of entries = " << nodeNumEntries_ << std::endl
                << "Node number of diagonals = " << nodeNumDiags_ << std::endl
                << "Node max number of entries = " << nodeMaxNumRowEntries_ << std::endl;
            if (indicesAreAllocated()) {
              out << "Node number of allocated entries = " << nodeNumAllocated_ << std::endl;
            }
            else {
              out << "Indices are not allocated." << std::endl;
            }
          }
          comm->barrier();
          comm->barrier();
          comm->barrier();
        }
      }
      // O(N) and O(NNZ) data
      if (vl == VERB_HIGH || vl == VERB_EXTREME) {
        TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
          ! hasRowInfo (), std::runtime_error, ": reduce verbosity level; "
          "graph row information was deleted at fillComplete().");
        for (int imageCtr = 0; imageCtr < numImages; ++imageCtr) {
          if (myImageID == imageCtr) {
            out << std::setw(width) << "Node ID"
                << std::setw(width) << "Global Row"
                << std::setw(width) << "Num Entries";
            if (vl == VERB_EXTREME) {
              out << " Entries";
            }
            out << std::endl;
            const LocalOrdinal lclNumRows =
              static_cast<LocalOrdinal> (this->getNodeNumRows ());
            for (LocalOrdinal r=0; r < lclNumRows; ++r) {
              const RowInfo rowinfo = this->getRowInfo (r);
              GlobalOrdinal gid = rowMap_->getGlobalElement(r);
              out << std::setw(width) << myImageID
                  << std::setw(width) << gid
                  << std::setw(width) << rowinfo.numEntries;
              if (vl == VERB_EXTREME) {
                out << " ";
                if (isGloballyIndexed()) {
                  ArrayView<const GlobalOrdinal> rowview = getGlobalView(rowinfo);
                  for (size_t j=0; j < rowinfo.numEntries; ++j) out << rowview[j] << " ";
                }
                else if (isLocallyIndexed()) {
                  ArrayView<const LocalOrdinal> rowview = getLocalView(rowinfo);
                  for (size_t j=0; j < rowinfo.numEntries; ++j) out << colMap_->getGlobalElement(rowview[j]) << " ";
                }
              }
              out << std::endl;
            }
          }
          comm->barrier();
          comm->barrier();
          comm->barrier();
        }
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  checkSizes (const SrcDistObject& source)
  {
    (void) source; // forestall "unused variable" compiler warnings

    // It's not clear what kind of compatibility checks on sizes can
    // be performed here.  Epetra_CrsGraph doesn't check any sizes for
    // compatibility.
    return true;
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<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;
    const char tfecfFuncName[] = "copyAndPermute";
    typedef CrsGraph<LO, GO, node_type> this_type;
    typedef RowGraph<LO, GO, node_type> row_graph_type;

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      permuteToLIDs.size() != permuteFromLIDs.size(), std::runtime_error,
      ": permuteToLIDs and permuteFromLIDs must have the same size.");
    // Make sure that the source object has the right type.  We only
    // actually need it to be a RowGraph, with matching first three
    // template parameters.  If it's a CrsGraph, we can use view mode
    // instead of copy mode to get each row's data.
    //
    // FIXME (mfh 07 Jul 2013) It should not be necessary for any of
    // the template parameters but GO to match.  GO has to match
    // because the graph has to send indices as global ordinals, if
    // the source and target graphs do not have the same column Map.
    // If LO doesn't match, the graphs could communicate using global
    // indices.  It could be possible that Node affects the graph's
    // storage format, but packAndPrepare should assume a common
    // communication format in any case.
    const row_graph_type* srcRowGraph = dynamic_cast<const row_graph_type*> (&source);
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      srcRowGraph == NULL, std::invalid_argument,
      ": The source object must be a RowGraph with matching first three "
      "template parameters.");

    // If the source object is actually a CrsGraph, we can use view
    // mode instead of copy mode to access the entries in each row,
    // if the graph is not fill complete.
    const this_type* srcCrsGraph = dynamic_cast<const this_type*> (&source);

    const map_type& srcRowMap = * (srcRowGraph->getRowMap ());
    const map_type& tgtRowMap = * (this->getRowMap ());
    const bool src_filled = srcRowGraph->isFillComplete ();
    Array<GO> row_copy;
    LO myid = 0;

    //
    // "Copy" part of "copy and permute."
    //
    if (src_filled || srcCrsGraph == NULL) {
      // If the source graph is fill complete, we can't use view mode,
      // because the data might be stored in a different format not
      // compatible with the expectations of view mode.  Also, if the
      // source graph is not a CrsGraph, we can't use view mode,
      // because RowGraph only provides copy mode access to the data.
      for (size_t i = 0; i < numSameIDs; ++i, ++myid) {
        const GO gid = srcRowMap.getGlobalElement (myid);
        size_t row_length = srcRowGraph->getNumEntriesInGlobalRow (gid);
        row_copy.resize (row_length);
        size_t check_row_length = 0;
        srcRowGraph->getGlobalRowCopy (gid, row_copy (), check_row_length);
        this->insertGlobalIndices (gid, row_copy ());
      }
    } else {
      for (size_t i = 0; i < numSameIDs; ++i, ++myid) {
        const GO gid = srcRowMap.getGlobalElement (myid);
        ArrayView<const GO> row;
        srcCrsGraph->getGlobalRowView (gid, row);
        this->insertGlobalIndices (gid, row);
      }
    }

    //
    // "Permute" part of "copy and permute."
    //
    if (src_filled || srcCrsGraph == NULL) {
      for (LO i = 0; i < permuteToLIDs.size (); ++i) {
        const GO mygid = tgtRowMap.getGlobalElement (permuteToLIDs[i]);
        const GO srcgid = srcRowMap.getGlobalElement (permuteFromLIDs[i]);
        size_t row_length = srcRowGraph->getNumEntriesInGlobalRow (srcgid);
        row_copy.resize (row_length);
        size_t check_row_length = 0;
        srcRowGraph->getGlobalRowCopy (srcgid, row_copy (), check_row_length);
        this->insertGlobalIndices (mygid, row_copy ());
      }
    } else {
      for (LO i = 0; i < permuteToLIDs.size (); ++i) {
        const GO mygid = tgtRowMap.getGlobalElement (permuteToLIDs[i]);
        const GO srcgid = srcRowMap.getGlobalElement (permuteFromLIDs[i]);
        ArrayView<const GO> row;
        srcCrsGraph->getGlobalRowView (srcgid, row);
        this->insertGlobalIndices (mygid, row);
      }
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  packAndPrepare (const SrcDistObject& source,
                  const Teuchos::ArrayView<const LocalOrdinal> &exportLIDs,
                  Teuchos::Array<GlobalOrdinal> &exports,
                  const Teuchos::ArrayView<size_t> & numPacketsPerLID,
                  size_t& constantNumPackets,
                  Distributor &distor)
  {
    using Teuchos::Array;
    const char tfecfFuncName[] = "packAndPrepare";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      exportLIDs.size() != numPacketsPerLID.size(), std::runtime_error,
      ": exportLIDs and numPacketsPerLID must have the same size.");
    typedef RowGraph<LocalOrdinal, GlobalOrdinal, node_type> row_graph_type;
    const row_graph_type& srcGraph = dynamic_cast<const row_graph_type&> (source);

    // We don't check whether src_graph has had fillComplete called,
    // because it doesn't matter whether the *source* graph has been
    // fillComplete'd. The target graph can not be fillComplete'd yet.
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      this->isFillComplete (), std::runtime_error,
      ": The target graph of an Import or Export must not be fill complete.");

    srcGraph.pack (exportLIDs, exports, numPacketsPerLID, constantNumPackets, distor);
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  pack (const Teuchos::ArrayView<const LocalOrdinal>& exportLIDs,
        Teuchos::Array<GlobalOrdinal>& exports,
        const Teuchos::ArrayView<size_t>& numPacketsPerLID,
        size_t& constantNumPackets,
        Distributor& distor) const
  {
    using Teuchos::Array;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    const char tfecfFuncName[] = "pack";
    (void) distor; // forestall "unused argument" compiler warning

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      exportLIDs.size() != numPacketsPerLID.size(), std::runtime_error,
      ": exportLIDs and numPacketsPerLID must have the same size.");

    const map_type& srcMap = * (this->getMap ());
    constantNumPackets = 0;

    // Set numPacketsPerLID[i] to the number of entries owned by the
    // calling process in (local) row exportLIDs[i] of the graph, that
    // the caller wants us to send out.  Compute the total number of
    // packets (that is, entries) owned by this process in all the
    // rows that the caller wants us to send out.
    size_t totalNumPackets = 0;
    Array<GO> row;
    for (LO i = 0; i < exportLIDs.size (); ++i) {
      const GO GID = srcMap.getGlobalElement (exportLIDs[i]);
      size_t row_length = this->getNumEntriesInGlobalRow (GID);
      numPacketsPerLID[i] = row_length;
      totalNumPackets += row_length;
    }

    exports.resize (totalNumPackets);

    // Loop again over the rows to export, and pack rows of indices
    // into the output buffer.
    size_t exportsOffset = 0;
    for (LO i = 0; i < exportLIDs.size (); ++i) {
      const GO GID = srcMap.getGlobalElement (exportLIDs[i]);
      size_t row_length = this->getNumEntriesInGlobalRow (GID);
      row.resize (row_length);
      size_t check_row_length = 0;
      this->getGlobalRowCopy (GID, row (), check_row_length);
      typename Array<GO>::const_iterator row_iter = row.begin();
      typename Array<GO>::const_iterator row_end = row.end();
      size_t j = 0;
      for (; row_iter != row_end; ++row_iter, ++j) {
        exports[exportsOffset+j] = *row_iter;
      }
      exportsOffset += row.size();
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  unpackAndCombine (const Teuchos::ArrayView<const LocalOrdinal> &importLIDs,
                    const Teuchos::ArrayView<const GlobalOrdinal> &imports,
                    const Teuchos::ArrayView<size_t> &numPacketsPerLID,
                    size_t constantNumPackets,
                    Distributor& /* distor */,
                    CombineMode /* CM */)
  {
    using Teuchos::ArrayView;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;

    // FIXME (mfh 02 Apr 2012) REPLACE combine mode has a perfectly
    // reasonable meaning, whether or not the matrix is fill complete.
    // It's just more work to implement.

    // We are not checking the value of the CombineMode input
    // argument.  For CrsGraph, we only support import/export
    // operations if fillComplete has not yet been called.  Any
    // incoming column-indices are inserted into the target graph. In
    // this context, CombineMode values of ADD vs INSERT are
    // equivalent. What is the meaning of REPLACE for CrsGraph? If a
    // duplicate column-index is inserted, it will be compressed out
    // when fillComplete is called.
    //
    // Note: I think REPLACE means that an existing row is replaced by
    // the imported row, i.e., the existing indices are cleared. CGB,
    // 6/17/2010

    const char tfecfFuncName[] = "unpackAndCombine: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      importLIDs.size() != numPacketsPerLID.size(), std::runtime_error,
      "importLIDs and numPacketsPerLID must have the same size.");
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
      isFillComplete (), std::runtime_error,
      "Import or Export operations are not allowed on the destination "
      "CrsGraph if it is fill complete.");
    size_t importsOffset = 0;

    typedef typename ArrayView<const LO>::const_iterator iter_type;
    iter_type impLIDiter = importLIDs.begin();
    iter_type impLIDend = importLIDs.end();

    for (size_t i = 0; impLIDiter != impLIDend; ++impLIDiter, ++i) {
      LO row_length = numPacketsPerLID[i];

      const GO* const row_raw = (row_length == 0) ? NULL : &imports[importsOffset];
      ArrayView<const GlobalOrdinal> row (row_raw, row_length);
      insertGlobalIndicesFiltered (this->getMap ()->getGlobalElement (*impLIDiter), row);
      importsOffset += row_length;
    }
  }


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  removeEmptyProcessesInPlace (const Teuchos::RCP<const map_type>& newMap)
  {
    using Teuchos::Comm;
    using Teuchos::null;
    using Teuchos::ParameterList;
    using Teuchos::RCP;

    // We'll set all the state "transactionally," so that this method
    // satisfies the strong exception guarantee.  This object's state
    // won't be modified until the end of this method.
    RCP<const map_type> rowMap, domainMap, rangeMap, colMap;
    RCP<import_type> importer;
    RCP<export_type> exporter;

    rowMap = newMap;
    RCP<const Comm<int> > newComm =
      (newMap.is_null ()) ? null : newMap->getComm ();

    if (! domainMap_.is_null ()) {
      if (domainMap_.getRawPtr () == rowMap_.getRawPtr ()) {
        // Common case: original domain and row Maps are identical.
        // In that case, we need only replace the original domain Map
        // with the new Map.  This ensures that the new domain and row
        // Maps _stay_ identical.
        domainMap = newMap;
      } else {
        domainMap = domainMap_->replaceCommWithSubset (newComm);
      }
    }
    if (! rangeMap_.is_null ()) {
      if (rangeMap_.getRawPtr () == rowMap_.getRawPtr ()) {
        // Common case: original range and row Maps are identical.  In
        // that case, we need only replace the original range Map with
        // the new Map.  This ensures that the new range and row Maps
        // _stay_ identical.
        rangeMap = newMap;
      } else {
        rangeMap = rangeMap_->replaceCommWithSubset (newComm);
      }
    }
    if (! colMap.is_null ()) {
      colMap = colMap_->replaceCommWithSubset (newComm);
    }

    // (Re)create the Export and / or Import if necessary.
    if (! newComm.is_null ()) {
      RCP<ParameterList> params = this->getNonconstParameterList (); // could be null
      //
      // The operations below are collective on the new communicator.
      //
      // (Re)create the Export object if necessary.  If I haven't
      // called fillComplete yet, I don't have a rangeMap, so I must
      // first check if the _original_ rangeMap is not null.  Ditto
      // for the Import object and the domain Map.
      if (! rangeMap_.is_null () &&
          rangeMap != rowMap &&
          ! rangeMap->isSameAs (*rowMap)) {
        if (params.is_null () || ! params->isSublist ("Export")) {
          exporter = rcp (new export_type (rowMap, rangeMap));
        }
        else {
          RCP<ParameterList> exportSublist = sublist (params, "Export", true);
          exporter = rcp (new export_type (rowMap, rangeMap, exportSublist));
        }
      }
      // (Re)create the Import object if necessary.
      if (! domainMap_.is_null () &&
          domainMap != colMap &&
          ! domainMap->isSameAs (*colMap)) {
        if (params.is_null () || ! params->isSublist ("Import")) {
          importer = rcp (new import_type (domainMap, colMap));
        } else {
          RCP<ParameterList> importSublist = sublist (params, "Import", true);
          importer = rcp (new import_type (domainMap, colMap, importSublist));
        }
      }
    } // if newComm is not null

    // Defer side effects until the end.  If no destructors throw
    // exceptions (they shouldn't anyway), then this method satisfies
    // the strong exception guarantee.
    exporter_ = exporter;
    importer_ = importer;
    rowMap_ = rowMap;
    // mfh 31 Mar 2013: DistObject's map_ is the row Map of a CrsGraph
    // or CrsMatrix.  CrsGraph keeps a redundant pointer (rowMap_) to
    // the same object.  We might want to get rid of this redundant
    // pointer sometime, but for now, we'll leave it alone and just
    // set map_ to the same object.
    this->map_ = rowMap;
    domainMap_ = domainMap;
    rangeMap_ = rangeMap;
    colMap_ = colMap;
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  bool
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  hasRowInfo () const
  {
    if (indicesAreAllocated () &&
        getProfileType () == StaticProfile &&
        k_rowPtrs_.dimension_0 () == 0) {
      return false;
    } else {
      return true;
    }
  }

  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalDiagOffsets (const Kokkos::View<size_t*, device_type, Kokkos::MemoryUnmanaged>& offsets) const
  {
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    const char tfecfFuncName[] = "getLocalDiagOffsets: ";

    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (! hasColMap (), std::runtime_error, "The graph must have a column Map.");
    const LO lclNumRows = static_cast<LO> (this->getNodeNumRows ());
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (static_cast<LO> (offsets.dimension_0 ()) < lclNumRows,
       std::invalid_argument, "offsets.dimension_0() = " <<
       offsets.dimension_0 () << " < getNodeNumRows() = " << lclNumRows << ".");

    const map_type& rowMap = * (this->getRowMap ());
    const map_type& colMap = * (this->getColMap ());

#ifdef HAVE_TPETRA_DEBUG
    bool allRowMapDiagEntriesInColMap = true;
    bool allDiagEntriesFound = true;
    bool allOffsetsCorrect = true;
    bool noOtherWeirdness = true;
    std::vector<std::pair<LO, size_t> > wrongOffsets;
#endif // HAVE_TPETRA_DEBUG

    // mfh 12 Mar 2016: LocalMap works on (CUDA) device.  It has just
    // the subset of Map functionality that we need below.
    auto lclRowMap = rowMap.getLocalMap ();
    auto lclColMap = colMap.getLocalMap ();

    // FIXME (mfh 16 Dec 2015) It's easy to thread-parallelize this
    // setup, at least on the host.  For CUDA, we have to use LocalMap
    // (that comes from each of the two Maps).

    const bool sorted = this->isSorted ();
    if (isFillComplete ()) {
      auto lclGraph = this->getLocalGraph ();
      Details::getGraphDiagOffsets (offsets, lclRowMap, lclColMap,
                                    lclGraph.row_map, lclGraph.entries,
                                    sorted);
    }
    else {
      for (LO lclRowInd = 0; lclRowInd < lclNumRows; ++lclRowInd) {
        const GO gblRowInd = lclRowMap.getGlobalElement (lclRowInd);
        const GO gblColInd = gblRowInd;
        const LO lclColInd = lclColMap.getLocalElement (gblColInd);

        if (lclColInd == Tpetra::Details::OrdinalTraits<LO>::invalid ()) {
#ifdef HAVE_TPETRA_DEBUG
          allRowMapDiagEntriesInColMap = false;
#endif // HAVE_TPETRA_DEBUG
          offsets[lclRowInd] = Tpetra::Details::OrdinalTraits<size_t>::invalid ();
        }
        else {
          const RowInfo rowInfo = this->getRowInfo (lclRowInd);
          if (static_cast<LO> (rowInfo.localRow) == lclRowInd &&
              rowInfo.numEntries > 0) {

            auto colInds = this->getLocalKokkosRowView (rowInfo);
            const size_t hint = 0; // not needed for this algorithm
            const size_t offset =
              KokkosSparse::findRelOffset (colInds, rowInfo.numEntries,
                                           lclColInd, hint, sorted);
            offsets(lclRowInd) = offset;

#ifdef HAVE_TPETRA_DEBUG
            // Now that we have what we think is an offset, make sure
            // that it really does point to the diagonal entry.  Offsets
            // are _relative_ to each row, not absolute (for the whole
            // (local) graph).
            Teuchos::ArrayView<const LO> lclColInds;
            try {
              this->getLocalRowView (lclRowInd, lclColInds);
            }
            catch (...) {
              noOtherWeirdness = false;
            }
            // Don't continue with error checking if the above failed.
            if (noOtherWeirdness) {
              const size_t numEnt = lclColInds.size ();
              if (offset >= numEnt) {
                // Offsets are relative to each row, so this means that
                // the offset is out of bounds.
                allOffsetsCorrect = false;
                wrongOffsets.push_back (std::make_pair (lclRowInd, offset));
              } else {
                const LO actualLclColInd = lclColInds[offset];
                const GO actualGblColInd = lclColMap.getGlobalElement (actualLclColInd);
                if (actualGblColInd != gblColInd) {
                  allOffsetsCorrect = false;
                  wrongOffsets.push_back (std::make_pair (lclRowInd, offset));
                }
              }
            }
#endif // HAVE_TPETRA_DEBUG
          }
          else {
            offsets(lclRowInd) = Tpetra::Details::OrdinalTraits<size_t>::invalid ();
#ifdef HAVE_TPETRA_DEBUG
            allDiagEntriesFound = false;
#endif // HAVE_TPETRA_DEBUG
          }
        }
      }
    }

#ifdef HAVE_TPETRA_DEBUG
    if (wrongOffsets.size () != 0) {
      std::ostringstream os;
      os << "Proc " << this->getComm ()->getRank () << ": Wrong offsets: [";
      for (size_t k = 0; k < wrongOffsets.size (); ++k) {
        os << "(" << wrongOffsets[k].first << ","
           << wrongOffsets[k].second << ")";
        if (k + 1 < wrongOffsets.size ()) {
          os << ", ";
        }
      }
      os << "]" << std::endl;
      std::cerr << os.str ();
    }
#endif // HAVE_TPETRA_DEBUG

#ifdef HAVE_TPETRA_DEBUG
    using Teuchos::reduceAll;
    using std::endl;
    Teuchos::RCP<const Teuchos::Comm<int> > comm = this->getComm ();
    const bool localSuccess =
      allRowMapDiagEntriesInColMap && allDiagEntriesFound && allOffsetsCorrect;
    const int numResults = 5;
    int lclResults[5];
    lclResults[0] = allRowMapDiagEntriesInColMap ? 1 : 0;
    lclResults[1] = allDiagEntriesFound ? 1 : 0;
    lclResults[2] = allOffsetsCorrect ? 1 : 0;
    lclResults[3] = noOtherWeirdness ? 1 : 0;
    // min-all-reduce will compute least rank of all the processes
    // that didn't succeed.
    lclResults[4] = ! localSuccess ? comm->getRank () : comm->getSize ();

    int gblResults[5];
    gblResults[0] = 0;
    gblResults[1] = 0;
    gblResults[2] = 0;
    gblResults[3] = 0;
    gblResults[4] = 0;
    reduceAll<int, int> (*comm, Teuchos::REDUCE_MIN,
                         numResults, lclResults, gblResults);

    if (gblResults[0] != 1 || gblResults[1] != 1 || gblResults[2] != 1
        || gblResults[3] != 1) {
      std::ostringstream os; // build error message
      os << "Issue(s) that we noticed (on Process " << gblResults[4] << ", "
        "possibly among others): " << endl;
      if (gblResults[0] == 0) {
        os << "  - The column Map does not contain at least one diagonal entry "
          "of the graph." << endl;
      }
      if (gblResults[1] == 0) {
        os << "  - On one or more processes, some row does not contain a "
          "diagonal entry." << endl;
      }
      if (gblResults[2] == 0) {
        os << "  - On one or more processes, some offsets are incorrect."
           << endl;
      }
      if (gblResults[3] == 0) {
        os << "  - One or more processes had some other error."
           << endl;
      }
      TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(true, std::runtime_error, os.str());
    }
#endif // HAVE_TPETRA_DEBUG
  }

  namespace { // (anonymous)

    // mfh 21 Jan 2016: This is useful for getLocalDiagOffsets (see
    // below).  The point is to avoid the deep copy between the input
    // Teuchos::ArrayRCP and the internally used Kokkos::View.  We
    // can't use UVM to avoid the deep copy with CUDA, because the
    // ArrayRCP is a host pointer, while the input to the graph's
    // getLocalDiagOffsets method is a device pointer.  Assigning a
    // host pointer to a device pointer is incorrect unless the host
    // pointer points to host pinned memory.  The goal is to get rid
    // of the Teuchos::ArrayRCP overload anyway, so we accept the deep
    // copy for backwards compatibility.
    //
    // We have to use template magic because
    // "staticGraph_->getLocalDiagOffsets(offsetsHosts)" won't compile
    // if device_type::memory_space is not Kokkos::HostSpace (as is
    // the case with CUDA).

    template<class DeviceType,
             const bool memSpaceIsHostSpace =
               std::is_same<typename DeviceType::memory_space,
                            Kokkos::HostSpace>::value>
    struct HelpGetLocalDiagOffsets {};

    template<class DeviceType>
    struct HelpGetLocalDiagOffsets<DeviceType, true> {
      typedef DeviceType device_type;
      typedef Kokkos::View<size_t*, Kokkos::HostSpace,
                           Kokkos::MemoryUnmanaged> device_offsets_type;
      typedef Kokkos::View<size_t*, Kokkos::HostSpace,
                           Kokkos::MemoryUnmanaged> host_offsets_type;

      static device_offsets_type
      getDeviceOffsets (const host_offsets_type& hostOffsets)
      {
        // Host and device are the same; no need to allocate a
        // temporary device View.
        return hostOffsets;
      }

      static void
      copyBackIfNeeded (const host_offsets_type& /* hostOffsets */,
                        const device_offsets_type& /* deviceOffsets */)
      { /* copy back not needed; host and device are the same */ }
    };

    template<class DeviceType>
    struct HelpGetLocalDiagOffsets<DeviceType, false> {
      typedef DeviceType device_type;
      // We have to do a deep copy, since host memory space != device
      // memory space.  Thus, the device View is managed (we need to
      // allocate a temporary device View).
      typedef Kokkos::View<size_t*, device_type> device_offsets_type;
      typedef Kokkos::View<size_t*, Kokkos::HostSpace,
                           Kokkos::MemoryUnmanaged> host_offsets_type;

      static device_offsets_type
      getDeviceOffsets (const host_offsets_type& hostOffsets)
      {
        // Host memory space != device memory space, so we must
        // allocate a temporary device View for the graph.
        return device_offsets_type ("offsets", hostOffsets.dimension_0 ());
      }

      static void
      copyBackIfNeeded (const host_offsets_type& hostOffsets,
                        const device_offsets_type& deviceOffsets)
      {
        Kokkos::deep_copy (hostOffsets, deviceOffsets);
      }
    };
  } // namespace (anonymous)


  template <class LocalOrdinal, class GlobalOrdinal, class Node, const bool classic>
  void
  CrsGraph<LocalOrdinal, GlobalOrdinal, Node, classic>::
  getLocalDiagOffsets (Teuchos::ArrayRCP<size_t>& offsets) const
  {
    typedef LocalOrdinal LO;
    const char tfecfFuncName[] = "getLocalDiagOffsets: ";
    TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC
      (! this->hasColMap (), std::runtime_error,
       "The graph does not yet have a column Map.");
    const LO myNumRows = static_cast<LO> (this->getNodeNumRows ());
    if (static_cast<LO> (offsets.size ()) != myNumRows) {
      // NOTE (mfh 21 Jan 2016) This means that the method does not
      // satisfy the strong exception guarantee (no side effects
      // unless successful).
      offsets.resize (myNumRows);
    }

    // mfh 21 Jan 2016: This method unfortunately takes a
    // Teuchos::ArrayRCP, which is host memory.  The graph wants a
    // device pointer.  We can't access host memory from the device;
    // that's the wrong direction for UVM.  (It's the right direction
    // for inefficient host pinned memory, but we don't want to use
    // that here.)  Thus, if device memory space != host memory space,
    // we allocate and use a temporary device View to get the offsets.
    // If the two spaces are equal, the template magic makes the deep
    // copy go away.
    typedef HelpGetLocalDiagOffsets<device_type> helper_type;
    typedef typename helper_type::host_offsets_type host_offsets_type;
    // Unmanaged host View that views the output array.
    host_offsets_type hostOffsets (offsets.getRawPtr (), myNumRows);
    // Allocate temp device View if host != device, else reuse host array.
    auto deviceOffsets = helper_type::getDeviceOffsets (hostOffsets);
    // NOT recursion; this calls the overload that takes a device View.
    this->getLocalDiagOffsets (deviceOffsets);
    helper_type::copyBackIfNeeded (hostOffsets, deviceOffsets);
  }

} // namespace Tpetra

//
// Explicit instantiation macros
//
// Must be expanded from within the Tpetra namespace!
//
#define TPETRA_CRSGRAPH_GRAPH_INSTANT(LO,GO,NODE) template class CrsGraph< LO , GO , NODE >;

// WARNING: These macros exist only for backwards compatibility.
// We will remove them at some point.
#define TPETRA_CRSGRAPH_SORTROWINDICESANDVALUES_INSTANT(S,LO,GO,NODE)
#define TPETRA_CRSGRAPH_MERGEROWINDICESANDVALUES_INSTANT(S,LO,GO,NODE)
#define TPETRA_CRSGRAPH_ALLOCATEVALUES1D_INSTANT(S,LO,GO,NODE)
#define TPETRA_CRSGRAPH_ALLOCATEVALUES2D_INSTANT(S,LO,GO,NODE)

#define TPETRA_CRSGRAPH_INSTANT(S,LO,GO,NODE)                    \
  TPETRA_CRSGRAPH_SORTROWINDICESANDVALUES_INSTANT(S,LO,GO,NODE)  \
  TPETRA_CRSGRAPH_MERGEROWINDICESANDVALUES_INSTANT(S,LO,GO,NODE) \
  TPETRA_CRSGRAPH_ALLOCATEVALUES1D_INSTANT(S,LO,GO,NODE)         \
  TPETRA_CRSGRAPH_ALLOCATEVALUES2D_INSTANT(S,LO,GO,NODE)

#endif // TPETRA_CRSGRAPH_DEF_HPP