GSparseMatrix.cpp 104 KB
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
/***************************************************************************
 *                  GSparseMatrix.cpp  -  sparse matrix class              *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2006-2011 by Jurgen Knodlseder                           *
 * ----------------------------------------------------------------------- *
 *                                                                         *
 *  This program is free software: you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation, either version 3 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 *                                                                         *
 * ----------------------------------------------------------------------- *
 * This class implements the compressed sparse column format. The          *
 * following arrays are allocated:                                         *
 *                                                                         *
 * m_rows     (n)  Number of rows                                          *
 * m_cols     (m)  Number of columns                                       *
 * m_data     (Ax) Holds all 'elements' non-zero values, in column order   *
 * m_colstart (Ap) Holds the index of the first element of each column     *
 * m_rowinx   (Ai) Holds the row indices for all elements                  *
 *                                                                         *
 * Column 'col' covers therefore [m_colstart[j], ..., m_colstart[j+1]-1]   *
 * Note that 'm_colstart' has m_cols+1 elements.                           *
 *                                                                         *
 ***************************************************************************/
/**
 * @file GSparseMatrix.cpp
 * @brief Sparse matrix class implementation
 * @author J. Knodlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cmath>
#include "GVector.hpp"
#include "GSparseMatrix.hpp"
#include "GSparseSymbolic.hpp"
#include "GSparseNumeric.hpp"

/* __ Method name definitions ____________________________________________ */
#define G_ACCESS1                          "GSparseMatrix::operator(int,int)"
#define G_ACCESS2                    "GSparseMatrix::operator(int,int) const"
#define G_OP_MUL_VEC                     "GSparseMatrix::operator* (GVector)"
#define G_OP_ADD                  "GSparseMatrix::operator+= (GSparseMatrix)"
#define G_OP_SUB                  "GSparseMatrix::operator-= (GSparseMatrix)"
#define G_OP_MAT_MUL              "GSparseMatrix::operator*= (GSparseMatrix)"
#define G_ADD_COL                       "GSparseMatrix::add_col(GVector,int)"
#define G_ADD_COL2              "GSparseMatrix::add_col(double*,int*int,int)"
#define G_CHOL_DECOMP                "GSparseMatrix::cholesky_decompose(int)"
#define G_CHOL_SOLVE            "GSparseMatrix::cholesky_solver(GVector,int)"
#define G_EXTRACT_ROW                       "GSparseMatrix::extract_row(int)"
#define G_EXTRACT_COL                       "GSparseMatrix::extract_col(int)"
#define G_INSERT_COL                 "GSparseMatrix::insert_col(GVector,int)"
#define G_INSERT_COL2       "GSparseMatrix::insert_col(double*,int*,int,int)"
#define G_STACK_INIT                     "GSparseMatrix::stack_init(int,int)"
#define G_STACK_PUSH "GSparseMatrix::stack_push_column(double*,int*,int,int)"
#define G_STACK_FLUSH                      "GSparseMatrix::stack_flush(void)"
#define G_CONSTRUCTOR               "GSparseMatrix::constructor(int,int,int)"
#define G_COPY_MEMBERS           "GSparseMatrix::copy_members(GSparseMatrix)"
#define G_ALLOC                      "GSparseMatrix::alloc_elements(int,int)"
#define G_FREE                        "GSparseMatrix::free_elements(int,int)"
#define G_REMOVE_ZERO              "GSparseMatrix::remove_zero_row_col(void)"
#define G_SYMPERM                       "cs_symperm(GSparseMatrix*,int*,int)"
#define G_TRANSPOSE                        "cs_transpose(GSparseMatrix*,int)"

/* __ Macros _____________________________________________________________ */
#define G_MIN(a,b) (((a) < (b)) ? (a) : (b))
#define G_MAX(a,b) (((a) > (b)) ? (a) : (b))

/* __ Coding definitions _________________________________________________ */
//#define G_USE_MEMCPY   // Do not use due to problems on 64 Bit systems
//#define G_USE_MEMMOVE  // Do not use due to problems on 64 Bit systems

/* __ Debug definitions __________________________________________________ */
//#define G_DEBUG_SPARSE_PENDING                    // Analyse pending values
//#define G_DEBUG_SPARSE_INSERTION                 // Analyse value insertion
//#define G_DEBUG_SPARSE_ADDITION                   // Analyse value addition
//#define G_DEBUG_SPARSE_COMPRESSION   // Analyse zero row/column compression
//#define G_DEBUG_SPARSE_MALLOC                  // Analyse memory management
//#define G_DEBUG_SPARSE_STACK_PUSH           // Analyse stack column pushing
//#define G_DEBUG_SPARSE_STACK_FLUSH         // Analyse stack column flushing



/*==========================================================================
 =                                                                         =
 =                   GSparseMatrix constructors/destructors                =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Matrix constructor
 *
 * @param[in] rows Number of rows in matrix.
 * @param[in] cols Number of columns in matrix.
 * @param[in] elements Number of elements for which memory should be allocated.
 *
 * First calls the void base class constructor that initialises all base
 * class members, then call the GSparseMatrix initialisation method and
 * finally construct the object.
 ***************************************************************************/
GSparseMatrix::GSparseMatrix(int rows, int cols, int elements) : GMatrixBase()
{
    // Initialise private members for clean destruction
    init_members();

    // Construct sparse matrix
    constructor(rows, cols, elements);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] m Matrix from which class should be instantiated.
 *
 * First calls the void base class copy constructor that copys all base
 * class members, then call the GSparseMatrix member copy method.
 * NOTE: The copy constructor does NOT fill a pending element.
 ***************************************************************************/
GSparseMatrix::GSparseMatrix(const GSparseMatrix& m) : GMatrixBase(m)
{
    // Initialise private members for clean destruction
    init_members();

    // Copy members
    copy_members(m);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Destructor
 ***************************************************************************/
GSparseMatrix::~GSparseMatrix(void)
{
    // Free members
    free_members();

    // Return
    return;
}


/*==========================================================================
 =                                                                         =
 =                         GSparseMatrix operators                         =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] m GSparseMatrix instance to be assigned
 ***************************************************************************/
GSparseMatrix& GSparseMatrix::operator= (const GSparseMatrix& m)
{
    // Execute only if object is not identical
    if (this != &m) {

        // Copy base class members
        this->GMatrixBase::operator=(m);

        // Free members
        free_members();

        // Initialise private members for clean destruction
        init_members();

        // Copy members
        copy_members(m);

    } // endif: object was not identical

    // Return
    return *this;
}


/***********************************************************************//**
 * @brief Access operator
 *
 * @param[in] row Matrix row.
 * @param[in] col Matrix column.
 *
 * @exception GException::out_of_range
 *            Row or column index out of range.
 ***************************************************************************/
double& GSparseMatrix::operator() (int row, int col)
{
    // Compile option: perform range check
    #if defined(G_RANGE_CHECK)
    if (row >= m_rows || col >= m_cols)
        throw GException::out_of_range(G_ACCESS1, row, col, m_rows, m_cols);
    #endif

    // Get element
    fill_pending();
    int inx = get_index(row,col);
    double* value;
    if (inx < 0) {
        value      = &m_fill_val;
        m_fill_row = row;
        m_fill_col = col;
    }
    else
        value = &(m_data[inx]);

    // Return element
    return *value;
}


/***********************************************************************//**
 * @brief Access operator (const version)
 *
 * @param[in] row Matrix row.
 * @param[in] col Matrix column.
 *
 * @exception GException::out_of_range
 *            Row or column index out of range.
 *
 * We need here the zero element to return also a pointer for 0.0 entry that
 * is not stored. Since we have the const version we don't have to care about
 * modification of this zero value.
 ***************************************************************************/
const double& GSparseMatrix::operator() (int row, int col) const
{
    // Compile option: perform range check
    #if defined(G_RANGE_CHECK)
    if (row >= m_rows || col >= m_cols)
        throw GException::out_of_range(G_ACCESS2, row, col, m_rows, m_cols);
    #endif

    // Get element
    int inx = get_index(row,col);
    double* value;
    if (inx < 0)
        value = (double*)&m_zero;
    else if (inx == m_elements)
        value = (double*)&m_fill_val;
    else
        value = (double*)&(m_data[inx]);

    // Return element
    return *value;
}


/***********************************************************************//**
 * @brief Vector multiplication
 *
 * @param[in] v GVector with which matrix is to be multiplied
 *
 * Performs sparse matrix*vector multiplication including any pending fill.
 ***************************************************************************/
GVector GSparseMatrix::operator* (const GVector& v) const
{
    // Raise an exception if the matrix and vector dimensions are not compatible
    if (m_cols != v.size())
        throw GException::matrix_vector_mismatch(G_OP_MUL_VEC, v.size(),
                                                 m_rows, m_cols);

    // Initialise result vector
    GVector result(m_rows);

    // Multiply only if there are elements in matrix
    if (m_elements > 0) {

        // Perform vector multiplication
        for (int col = 0; col < m_cols; ++col) {
            int     i_start    = m_colstart[col];
            int     i_stop     = m_colstart[col+1];
            double* ptr_data   = m_data   + i_start;
            int*    ptr_rowinx = m_rowinx + i_start;
            for (int i = i_start; i < i_stop; ++i)
                result[*ptr_rowinx++] += *ptr_data++ * v[col];
        }

        // If fill is pending then add-in also this element into the product
        if (m_fill_val != 0.0) {
            result[m_fill_row] += m_fill_val * v[m_fill_col];
            #if defined(G_DEBUG_SPARSE_PENDING)
            std::cout << G_OP_MUL_VEC << ": pending value " << m_fill_val
                      << " for location (" <<  m_fill_row << "," << m_fill_col
                      << ") has been used." << std::endl;
            #endif
        }

    } // endif: there were elements in matrix

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Equalty operator
 *
 * @param[in] m Matrix to compare with.
 *
 * Two matrixes are considered equal if they have the same dimensions and
 * identicial elements. The return value is 1 if the matrices are identical,
 * 0 otherwise.
 * TODO: Implement native sparse code
 ***************************************************************************/
int GSparseMatrix::operator== (const GSparseMatrix &m) const
{
    // Initalise the result to 'equal matrices'
    int result = 1;

    // Perform comparison (only if matrix dimensions are identical)
    if (m_rows == m.m_rows && m_cols == m.m_cols) {

        // Loop over all matrix elements
        for (int row = 0; row < m_rows; ++row) {
            for (int col = 0; col < m_cols; ++col) {
                if ((*this)(row,col) != m(row,col)) {
                    result = 0;
                    break;
                }
            }
            if (!result)
                break;
        }
    }
    else
      result = 0;

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Unequalty operator
 *
 * @param[in] m Matrix to compare with.
 *
 * Two matrixes are considered unequal if they have different dimensions or
 * differing elements. The return value is 1 if the matrices are not
 * identical and 0 if they are identical.
 * TODO: Implement native sparse code
 ***************************************************************************/
int GSparseMatrix::operator!= (const GSparseMatrix &m) const
{
    // Initalise the result to 'equal matrices'
    int result = 0;

    // Perform comparison (only if matrix dimensions are identical)
    if (m_rows == m.m_rows && m_cols == m.m_cols) {

        // Loop over all matrix elements
        for (int row = 0; row < m_rows; ++row) {
            for (int col = 0; col < m_cols; ++col) {
                if ((*this)(row,col) != m(row,col)) {
                    result = 1;
                    break;
                }
            }
            if (!result)
                break;
        }
    }
    else
      result = 1;

    // Return result
    return result;
}


/***********************************************************************//**
 * @brief Unary matrix addition operator
 *
 * @param[in] m Matrix to be added.
 *
 * TODO: Implement native sparse code
 ***************************************************************************/
GSparseMatrix& GSparseMatrix::operator+= (const GSparseMatrix& m)
{
    // Raise an exception if the matrix dimensions are not compatible
    if (m_rows != m.m_rows || m_cols != m.m_cols)
        throw GException::matrix_mismatch(G_OP_ADD, m_rows, m_cols,
                                          m.m_rows, m.m_cols);

    // Perform inplace matrix addition using vectors
    for (int col = 0; col < m_cols; ++col) {
        GVector v_result  = extract_col(col);
        GVector v_operand = m.extract_col(col);
        v_result += v_operand;
        insert_col(v_result, col);
    }

    // Return result
    return *this;
}


/***********************************************************************//**
 * @brief Unary matrix subtraction operator
 *
 * @param[in] m Matrix to be subtracted.
 *
 * TODO: Implement native sparse code
 ***************************************************************************/
GSparseMatrix& GSparseMatrix::operator-= (const GSparseMatrix& m)
{
    // Raise an exception if the matrix dimensions are not compatible
    if (m_rows != m.m_rows || m_cols != m.m_cols)
        throw GException::matrix_mismatch(G_OP_SUB, m_rows, m_cols,
                                          m.m_rows, m.m_cols);

    // Perform inplace matrix subtraction
    for (int col = 0; col < m_cols; ++col) {
      GVector v_result  = extract_col(col);
      GVector v_operand = m.extract_col(col);
      v_result -= v_operand;
      insert_col(v_result, col);
    }

    // Return result
    return *this;
}


/***********************************************************************//**
 * @brief Unary matrix multiplication operator
 *
 * @param[in] m Matrix to be multiplied.
 *
 * TODO: Implement native sparse code
 ***************************************************************************/
GSparseMatrix& GSparseMatrix::operator*= (const GSparseMatrix& m)
{
    // Raise an exception if the matrix dimensions are not compatible
    if (m_cols != m.m_rows || m_rows != m.m_cols)
        throw GException::matrix_mismatch(G_OP_MAT_MUL, m_rows, m_cols,
                                          m.m_rows, m.m_cols);

    // Allocate result matrix
    GSparseMatrix result(m_rows, m.m_cols);

    // Multiply only if there are elements in both matrices
    if (m_elements > 0 && m.m_elements > 0) {

        // Loop over all elements of result matrix
        for (int row = 0; row < m_rows; ++row) {
            for (int col = 0; col < m.m_cols; ++col) {
                double sum = 0.0;
                for (int i = 0; i < m_cols; ++i)
                    sum += (*this)(row,i) * m(i,col);
                result(row,col) = sum;
            }
        }

    }

    // Assign result
    *this = result;

    // Return result
    return *this;
}


/*==========================================================================
 =                                                                         =
 =                      GSparseMatrix public methods                       =
 =                                                                         =
 ==========================================================================*/

/***************************************************************************
 *                         Add vector to matrix column                     *
 * ----------------------------------------------------------------------- *
 * This is the main driver routine to add data to a matrix. It handles     *
 * both normal and stack-based filled. Note that there is another instance *
 * of this function that takes a compressed array.                         *
 ***************************************************************************/
void GSparseMatrix::add_col(const GVector& v, int col)
{
  // Debug header
  #if defined(G_DEBUG_SPARSE_ADDITION)
  cout << "GSparseMatrix::add_col([" << v << "], " << col << "):" << endl;
  cout << " In Data : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " In Row .: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " In Col .: ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  #endif

  // Initialise number of non-zero elements to 0
  int non_zero = 0;

  // If we have a stack then try to push vector on stack first. Note that
  // stack_push_column does its own argument verifications, so to avoid
  // double checking we don't do anything before this call ...
  if (m_stack_data != NULL) {
    non_zero = stack_push_column(v, col);
    if (non_zero == 0)
      return;
  }

  // ... otherwise check first the arguments and determine the number of
  // non-zero elements in vector
  else {

    // Raise an exception if the column index is invalid
    #if defined(G_RANGE_CHECK)
    if (col >= m_cols)
      throw GException::out_of_range(G_ADD_COL, 0, col, m_rows, m_cols);
    #endif

    // Raise an exception if the matrix and vector dimensions are incompatible
    if (m_rows != v.size())
      throw GException::matrix_vector_mismatch(G_ADD_COL, v.size(), m_rows, m_cols);

    // Determine number of non-zero elements in vector
    non_zero = v.non_zeros();
  }

  // Extract vector for column, add elements, and re-insert vector (only if
  // vector to insert has non-zeros)
  if (non_zero > 0) {

    // Copy input vector
    GVector column = v;

    // Add elements to vector
    for (int i = m_colstart[col]; i < m_colstart[col+1]; ++i)
      column[m_rowinx[i]] += m_data[i];

    // If there is a pending element then put it in the vector
    if (m_fill_val != 0.0 && m_fill_col == col)
      column[m_fill_row] += m_fill_val;

    // Insert vector into matrix
    insert_col(column, col);

  }

  // Debugging: show sparse matrix after addition
  #if defined(G_DEBUG_SPARSE_ADDITION)
  cout << " Out Data: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " Out Row : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " Out Col : ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  #endif

  // Return
  return;
}


/***************************************************************************
 *                   Add compressed array to matrix column                 *
 * ----------------------------------------------------------------------- *
 * This is the main driver routine to add data to a matrix. It handles     *
 * both normal and stack-based filled. Note that there is another instance *
 * of this function that takes a vector.                                   *
 ***************************************************************************/
void GSparseMatrix::add_col(const double* values, const int* rows, 
                            int number, int col)
{
  // Debug header
  #if defined(G_DEBUG_SPARSE_ADDITION)
  cout << "GSparseMatrix::add_col(v, i, n, " << col << "):" << endl;
  cout << " Matrix Data : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " Matrix Row .: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " Matrix Col .: ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  cout << " Array Data .: ";
  for (int i = 0; i < number; ++i)
    cout << values[i] << " ";
  cout << endl << " Array Row ..: ";
  for (int i = 0; i < number; ++i)
    cout << rows[i] << " ";
  cout << endl;
  #endif

  // If we have a stack then try to push elements on stack first. Note that
  // stack_push_column does its own argument verifications, so to avoid
  // double checking we don't do anything before this call ...
  if (m_stack_data != NULL) {
    number = stack_push_column(values, rows, number, col);
    if (number == 0)
      return;
  }

  // ... otherwise check the arguments
  else {
    // If the array is empty there is nothing to do
    if (!values || !rows || (number < 1))
      return;

    // Raise an exception if the column index is invalid
    #if defined(G_RANGE_CHECK)
    if (col >= m_cols)
      throw GException::out_of_range(G_ADD_COL2, 0, col, m_rows, m_cols);
    #endif

    // Raise an exception if the index array seems incompatible with matrix 
    // dimensions
    if (rows[number-1] >= m_rows)
      throw GException::matrix_vector_mismatch(G_ADD_COL2, rows[number-1], m_rows, m_cols);
  } // endelse: there was no stack

  // Get indices of column in matrix
  int i_start = m_colstart[col];
  int i_stop  = m_colstart[col+1];

  // Case A: the column exists in the matrix, so mix new elements with existing
  // data
  if (i_start < i_stop) {

    // Allocate workspace to hold combined column
    int     wrk_size   = number + i_stop - i_start;
    double* wrk_double = new double[wrk_size];
    int*    wrk_int    = new int[wrk_size];

    // Mix matrix column with specified data
    int num_mix;
    mix_column(&(m_data[i_start]), &(m_rowinx[i_start]), i_stop-i_start,
               values, rows, number,
               wrk_double, wrk_int, &num_mix);

    // Insert mixed column
    insert_col(wrk_double, wrk_int, num_mix, col);

    // Free workspace
    delete [] wrk_int;
    delete [] wrk_double;

  } // endif: Case A

  // Case B: the column does not yet exist in the matrix, so just insert it
  else
    insert_col(values, rows, number, col);

  // Debugging: show sparse matrix after insertion
  #if defined(G_DEBUG_SPARSE_ADDITION)
  cout << " Out Data: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " Out Row : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " Out Col : ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  #endif

  // Return
  return;
}


/***************************************************************************
 *                   GSparseMatrix Cholesky decomposition                  *
 * ----------------------------------------------------------------------- *
 * Cholesky decomposition of a sparse matrix. The decomposition is stored  *
 * within the GSparseMatrix without destroying the original matrix.        *
 ***************************************************************************/
void GSparseMatrix::cholesky_decompose(int compress)
{
  // Save original matrix size
  int matrix_rows = m_rows;
  int matrix_cols = m_cols;

  // Delete any existing symbolic and numeric analysis object and reset
  // pointers
  if (m_symbolic != NULL) delete (GSparseSymbolic*)m_symbolic;
  if (m_numeric  != NULL) delete (GSparseNumeric*)m_numeric;
  m_symbolic = NULL;
  m_numeric  = NULL;

  // Allocate symbolic analysis object
  GSparseSymbolic* symbolic = new GSparseSymbolic();

  // Declare numeric analysis object. We don't allocate one since we'll
  // throw it away at the end of the function (the L matrix will be copied
  // in this object)
  GSparseNumeric numeric;

  // Fill pending element into matrix
  fill_pending();

  // Remove rows and columns containing only zeros if matrix compression
  // has been selected
  if (compress)
    remove_zero_row_col();

  // Ordering an symbolic analysis of matrix. This sets up an array 'pinv'
  // which contains the fill-in reducing permutations
  symbolic->cholesky_symbolic_analysis(1, *this);

  // Store symbolic pointer in sparse matrix object
  m_symbolic = (void*)symbolic;

  // Perform numeric Cholesky decomposition
  numeric.cholesky_numeric_analysis(*this, *symbolic);

  // Copy L matrix into this object
  free_elements(0, m_elements);
  alloc_elements(0, numeric.m_L->m_elements);
  for (int i = 0; i < m_elements; ++i) {
    m_data[i]   = numeric.m_L->m_data[i];
    m_rowinx[i] = numeric.m_L->m_rowinx[i];
  }
  for (int col = 0; col <= m_cols; ++col)
    m_colstart[col] = numeric.m_L->m_colstart[col];

  // Insert zero rows and columns if they have been removed previously.
  if (compress)
    insert_zero_row_col(matrix_rows, matrix_cols);

  // Return
  return;
}


/***********************************************************************//**
 * @brief Cholesky solver
 *
 * @param[in] v Solution vector.
 * @param[in] compress Request matrix compression.
 *
 * Solves the linear equation A*x=b using a Cholesky decomposition of A.
 * This function is to be applied on a GSparseMatrix matrix for which a
 * Choleksy factorization has been produced using 'cholesky_decompose'.
 ***************************************************************************/
GVector GSparseMatrix::cholesky_solver(const GVector& v, int compress)
{
    // Declare loop variables
//    int row;
//    int col;
//    int c_row;
//    int c_col;

    // Dump header
    #if defined(G_DEBUG_SPARSE_COMPRESSION)
    std::cout << "GSparseMatrix::cholesky_solver" << std::endl;
    std::cout << " Input vector .....: " << v << std::endl;
    #endif

    // Raise an exception if the matrix and vector dimensions are incompatible
    if (m_rows != v.size())
        throw GException::matrix_vector_mismatch(G_CHOL_SOLVE, v.size(),
                                                 m_rows, m_cols);
    // Raise an exception if there is no symbolic pointer
    if (!m_symbolic)
        throw GException::matrix_not_factorised(G_CHOL_SOLVE, 
                                                "Cholesky decomposition");

    // Get symbolic pointer
    GSparseSymbolic* symbolic = (GSparseSymbolic*)m_symbolic;

    // Raise an exception if there is no permutation
    if (!symbolic->m_pinv)
        throw GException::matrix_not_factorised(G_CHOL_SOLVE, 
                                                "Cholesky decomposition");

    // Flag row and column compression
    int row_compressed = (m_rowsel != NULL && m_num_rowsel < m_rows);
    int col_compressed = (m_colsel != NULL && m_num_colsel < m_cols);

    // Decide if we need a compression algorithm or not
    int no_zero = !(compress && (row_compressed || col_compressed));

    // Allocate vector for permutation and result vector
    GVector result(m_cols);

    // Setup pointers to L matrix and x vector
    int*    Lp = m_colstart;
    int*    Li = m_rowinx; 
    double* Lx = m_data;

    // Case A: no zero-row/col compression needed
    if (no_zero) {

        // Declare working vector
        GVector x(m_rows);

        // Perform inverse vector permutation
        for (int i = 0; i < v.size(); ++i)
            x[symbolic->m_pinv[i]] = v[i];  

        // Inplace solve L\x=x
        for (int col = 0; col < m_cols; ++col) {            // loop over columns
            x[col] /= Lx[Lp[col]];                          // divide by diag.
            for (int p = Lp[col]+1; p < Lp[col+1]; p++)     // loop over elements
                x[Li[p]] -= Lx[p] * x[col];
        }

        // Inplace solve L'\x=x
        for (int col = m_cols-1; col >= 0; --col) {         // loop over columns
            for (int p = Lp[col]+1; p < Lp[col+1]; p++)     // loop over elements
                x[col] -= Lx[p] * x[Li[p]];
                x[col] /= Lx[Lp[col]];
        }

        // Perform vector permutation
        for (int i = 0; i < m_cols; ++i)
            result[i] = x[symbolic->m_pinv[i]];

    } // endif: Case A

    // Case B: zero-row/column compression requested
    else {

        // Allocate row and column mapping arrays
        int* row_map = new int[m_rows];
        int* col_map = new int[m_cols];

        // Setup row mapping array that maps original matrix rows into compressed
        // matrix rows. An entry of -1 indicates that the row should be dropped.
        // If no selection exists then setup an identity map.
        if (row_compressed) {
            for (int row = 0; row < m_rows; ++row)
                row_map[row] = -1;
            for (int c_row = 0; c_row < m_num_rowsel; ++c_row)
                row_map[m_rowsel[c_row]] = c_row;
        }
        else {
            for (int row = 0; row < m_rows; ++row)
                row_map[row] = row;
        }
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Row mapping ......:";
        for (int row = 0; row < m_rows; ++row)
            std::cout << " " << row_map[row];
        std::cout << std::endl;
        #endif

        // Setup column mapping array that maps original matrix column into compressed
        // matrix columns. An entry of -1 indicates that the column should be dropped
        // If no selection exists then setup an identity map.
        if (col_compressed) {
            for (int col = 0; col < m_cols; ++col)
                col_map[col] = -1;
            for (int c_col = 0; c_col < m_num_colsel; ++c_col)
                col_map[m_colsel[c_col]] = c_col;
        }
        else {
            for (int col = 0; col < m_cols; ++col)
                col_map[col] = col;
        }
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Column mapping ...:";
        for (int col = 0; col < m_cols; ++col)
            std::cout << " " << col_map[col];
        std::cout << std::endl;
        #endif

        // Declare working vector
        GVector x(row_compressed ? m_num_rowsel : m_rows);

        // Compress input vector v -> c_v if required
        if (m_rowsel != NULL && m_num_rowsel < m_rows) {
            for (int c_row = 0; c_row < m_num_rowsel; ++c_row)
                x[c_row] = v[m_rowsel[c_row]];
        }
        else
            x = v;
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Compressed vector : " << x << std::endl;
        #endif

        // Perform inverse permutation
        x = iperm(x, symbolic->m_pinv);
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Permutated vector : " << x << std::endl;
        #endif

        // Inplace solve L\x=x. The column and row maps are just use to see which
        // columns or rows should be skipped in the calculations.
        for (int col = 0; col < m_cols; ++col) {              // loop over columns
            int c_col = col_map[col];
            if (c_col >= 0) {                                 // use only non-zero cols
                x[c_col] /= Lx[Lp[col]];                      // divide by diag.
                for (int p = Lp[col]+1; p < Lp[col+1]; p++) { // loop over elements
                    int c_row = row_map[Li[p]];
                    if (c_row >= 0)                           // use only non-zero rows
                        x[c_row] -= Lx[p] * x[c_col];
                }
            }
        }
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Solve Lx=x .......: " << x << std::endl;
        #endif

        // Inplace solve L'\x=x. The column and row maps are just use to see which
        // columns or rows should be skipped in the calculations.
        for (int col = m_cols-1; col >= 0; --col) {           // loop over columns
            int c_col = col_map[col];
            if (c_col >= 0) {                                 // use only non-zero cols
                for (int p = Lp[col]+1; p < Lp[col+1]; p++) { // loop over elements
                    int c_row = row_map[Li[p]];
                    if (c_row >= 0)                           // use only non-zero rows
                        x[c_col] -= Lx[p] * x[c_row];
                }
                x[c_col] /= Lx[Lp[col]];
            }
        }
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Solve L'x=x ......: " << x << std::endl;
        #endif

        // Perform vector permutation
        x = perm(x, symbolic->m_pinv);
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Permutated vector : " << x << std::endl;
        #endif

        // If column compression has been performed the expand the result vector
        // accordingly
        if (m_colsel != NULL && m_num_colsel < m_cols) {
            for (int c_col = 0; c_col < m_num_colsel; ++c_col)
                result[m_colsel[c_col]] = x[c_col];
        }
        else
            result = x;
        #if defined(G_DEBUG_SPARSE_COMPRESSION)
        std::cout << " Restored vector ..: " << result << std::endl;
        #endif

        // Free mapping arrays
        delete [] row_map;
        delete [] col_map;

    } // endelse: Case B

    // Return result vector
    return result;
}


/***************************************************************************
 *                       GSparseMatrix Cholesky invert                     *
 * ----------------------------------------------------------------------- *
 * Inplace matrix inversion using the Cholesky decomposition.              *
 ***************************************************************************/
void GSparseMatrix::cholesky_invert(int compress)
{
  // Generate Cholesky decomposition of matrix
  cholesky_decompose(compress);

  // Allocate result matrix and unit vector
  GSparseMatrix result(m_rows, m_cols);
  GVector       unit(m_rows);

  // Column-wise solving of the problem
  for (int col = 0; col < m_cols; ++col) {

    // Set unit vector
    unit[col] = 1.0;

    // Solve for column
    GVector x = cholesky_solver(unit, compress);

    // Insert column in matrix
    result.insert_col(x, col);

    // Clear unit vector for next round
    unit[col] = 0.0;

  }

  *this = result;

  // Return
  return;
}


/***********************************************************************//**
 * @brief Set all matrix elements to 0
 ***************************************************************************/
void GSparseMatrix::clear(void)
{
    // Free memory
    free_elements(0, m_elements);

    // Initialise column start indices to 0
    for (int col = 0; col <= m_cols; ++col)
         m_colstart[col] = 0;

    // Return
    return;
}


/***************************************************************************
 *                     Extract row from matrix into vector                 *
 * ----------------------------------------------------------------------- *
 ***************************************************************************/
GVector GSparseMatrix::extract_row(int row) const
{
  // Raise an exception if the row index is invalid
  #if defined(G_RANGE_CHECK)
  if (row >= m_rows)
    throw GException::out_of_range(G_EXTRACT_ROW, row, 0, m_rows, m_cols);
  #endif

  // Create result vector
  GVector result(m_cols);

  // Loop over all columns to extract data
  for (int col = 0; col < m_cols; ++col) {

    // Get the start and stop of the elements
    int i_start = m_colstart[col];
    int i_stop  = m_colstart[col+1];

    // Search requested row in elements
    int i;
    for (i = i_start; i < i_stop; ++i) {
      if (m_rowinx[i] == row)
        break;
    }

    // Copy element if we found one
    if (i < i_stop)
      result[col] = m_data[i];

  } // endfor: looped over all columns

  // If there is a pending element then put it in the vector
  if (m_fill_val != 0.0 && m_fill_row == row)
    result[m_fill_col] = m_fill_val;

  // Return vector
  return result;

}


/***************************************************************************
 *                   Extract column from matrix into vector                *
 ***************************************************************************/
GVector GSparseMatrix::extract_col(int col) const
{
  // Raise an exception if the column index is invalid
  #if defined(G_RANGE_CHECK)
  if (col >= m_cols)
    throw GException::out_of_range(G_EXTRACT_COL, 0, col, m_rows, m_cols);
  #endif

  // Create result vector
  GVector result(m_rows);

  // Get the start and stop of the elements
  int i_start = m_colstart[col];
  int i_stop  = m_colstart[col+1];

  // Extract elements into vector
  for (int i = i_start; i < i_stop; ++i)
    result[m_rowinx[i]] = m_data[i];

  // If there is a pending element then put it in the vector
  if (m_fill_val != 0.0 && m_fill_col == col)
    result[m_fill_row] = m_fill_val;

  // Return vector
  return result;
}


/***********************************************************************//**
 * @brief Returns fill of matrix
 *
 * The fill of a matrix is defined as the number non-zero elements devided
 * by the number of total elements. By definiton, the fill is comprised
 * in the interval [0,..,1]. The fill of an undefined matrix is defined to
 * be 0.
 ***************************************************************************/
double GSparseMatrix::fill() const
{
    // Initialise result
    double result = 0.0;

    // Compute matrix size
    int size = m_rows*m_cols;

    // Continue only if matrix has elements
    if (size > 0) {

        // Determine number of elements in matrix
        int num = (m_fill_val == 0.0) ? m_elements : m_elements + 1;

        // Compute fill
        result = double(num) / double(size);

    } // endif: there were elements in matrix

    // Return fill
    return result;
}


/***************************************************************************
 *                      Insert vector column into matrix                   *
 * ----------------------------------------------------------------------- *
 * This is the main driver routine to insert data into a matrix. Note that *
 * there is another instance of this function that takes a compressed      *
 * array.                                                                  *
 ***************************************************************************/
void GSparseMatrix::insert_col(const GVector& v, int col)
{
  // Debug header
  #if defined(G_DEBUG_SPARSE_INSERTION)
  cout << "GSparseMatrix::insert_col([" << v << "], " << col << "):" << endl;
  cout << " In Data : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " In Row .: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " In Col .: ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  #endif

  // Raise an exception if the column index is invalid
  #if defined(G_RANGE_CHECK)
  if (col >= m_cols)
    throw GException::GException::out_of_range(G_INSERT_COL, 0, col, m_rows, m_cols);
  #endif

  // Raise an exception if the matrix and vector dimensions are not compatible
  if (m_rows != v.size())
    throw GException::matrix_vector_mismatch(G_INSERT_COL, v.size(), m_rows, m_cols);

  // If there is a pending element for this column then delete it since
  // the vector overwrites this element
  if (m_fill_val != 0.0 && m_fill_col == col) {
    #if defined(G_DEBUG_SPARSE_PENDING)
    cout << G_INSERT_COL << ": pending value " << m_fill_val << 
         " for location (" << m_fill_row << "," << m_fill_col << 
         ") became obsolete" << endl;
    #endif
    m_fill_val = 0.0;
    m_fill_row = 0;
    m_fill_col = 0;
  }

  // Determine the number of non-zero elements in the vector
  int n_vector = 0;
  for (int row = 0; row < m_rows; ++row) {
    if (v[row] != 0.0)
      n_vector++;
  }

  // Get the start and stop indices of the actual column and compute
  // the number of exisiting elements in the column
  int i_start = m_colstart[col];
  int i_stop  = m_colstart[col+1];
  int n_exist = i_stop - i_start;

  // Compute the size difference for the new matrix. It is positive if
  // the number of non-zero entries in the vector is larger than the
  // number of non-zero entries in the matrix (in this case we have to
  // increase the matrix size).
  int n_diff = n_vector - n_exist;

  // If we need space then allocate it, if we have to much space then free it
  if (n_diff > 0) {
    alloc_elements(i_start, n_diff);
    #if defined(G_DEBUG_SPARSE_INSERTION)
    cout << " Insert .: " << n_diff << " elements at index " << i_start << endl;
    #endif
  }
  else if (n_diff < 0) {
    free_elements(i_start, -n_diff);
    #if defined(G_DEBUG_SPARSE_INSERTION)
    cout << " Remove .: " << -n_diff << " elements at index " << i_start << endl;
    #endif
  }

  // Insert the vector elements in the matrix
  if (n_vector > 0) {
    for (int row = 0, i = i_start; row < m_rows; ++row) {
      if (v[row] != 0.0) {
        m_data[i]   = v[row];
        m_rowinx[i] = row;
        i++;
      }
    }
  }

  // Update column start indices
  for (int i = col+1; i <= m_cols; ++i)
    m_colstart[i] += n_diff;

  // Debugging: show sparse matrix after insertion
  #if defined(G_DEBUG_SPARSE_INSERTION)
  cout << " Out Data: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " Out Row : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " Out Col : ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  #endif

  // Return
  return;
}


/***************************************************************************
 *                    Insert compressed array into matrix                  *
 * ----------------------------------------------------------------------- *
 * This is the main driver routine to insert data into a matrix. Note that *
 * there is another instance of this function that takes a vector.         *
 ***************************************************************************/
void GSparseMatrix::insert_col(const double* values, const int* rows, 
                               int number, int col)
{
  // Debug header
  #if defined(G_DEBUG_SPARSE_INSERTION)
  cout << "GSparseMatrix::insert_col(v, i, n, " << col << "):" << endl;
  cout << " Matrix Data : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " Matrix Row .: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " Matrix Col .: ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  cout << " Array Data .: ";
  for (int i = 0; i < number; ++i)
    cout << values[i] << " ";
  cout << endl << " Array Row ..: ";
  for (int i = 0; i < number; ++i)
    cout << rows[i] << " ";
  cout << endl;
  #endif

  // Raise an exception if the column index is invalid
  #if defined(G_RANGE_CHECK)
  if (col >= m_cols)
    throw GException::out_of_range(G_INSERT_COL2, 0, col, m_rows, m_cols);
  #endif

  // Raise an exception if the index array seems incompatible with matrix 
  // dimensions
  if (rows[number-1] >= m_rows)
    throw GException::matrix_vector_mismatch(G_INSERT_COL2, rows[number-1], m_rows, m_cols);

  // If there is a pending element for this column then delete it since
  // the vector overwrites this element
  if (m_fill_val != 0.0 && m_fill_col == col) {
    #if defined(G_DEBUG_SPARSE_PENDING)
    cout << G_INSERT_COL2 << ": pending value " << m_fill_val << 
         " for location (" << m_fill_row << "," << m_fill_col << 
         ") became obsolete" << endl;
    #endif
    m_fill_val = 0.0;
    m_fill_row = 0;
    m_fill_col = 0;
  }

  // Get the start and stop indices of the actual column and compute
  // the number of exisiting elements in the column
  int i_start = m_colstart[col];
  int i_stop  = m_colstart[col+1];
  int n_exist = i_stop - i_start;

  // If the array is empty then make sure that the number of elements is 0 
  // (we then just delete the existing column)
  if (!values || !rows)
    number = 0;

  // Compute the size difference for the new matrix. It is positive if
  // the number of non-zero entries in the array is larger than the
  // number of non-zero entries in the matrix (in this case we have to
  // increase the matrix size).
  int n_diff = number - n_exist;

  // If we need space then allocate it, if we have to much space then free it
  if (n_diff > 0) {
    alloc_elements(i_start, n_diff);
    #if defined(G_DEBUG_SPARSE_INSERTION)
    cout << " Insert .: " << n_diff << " elements at index " << i_start << endl;
    #endif
  }
  else if (n_diff < 0) {
    free_elements(i_start, -n_diff);
    #if defined(G_DEBUG_SPARSE_INSERTION)
    cout << " Remove .: " << -n_diff << " elements at index " << i_start << endl;
    #endif
  }

  // Insert the array elements into the matrix
  if (number > 0) {
    for (int row = 0, i = i_start; row < number; ++row, ++i) {
      m_data[i]   = values[row];
      m_rowinx[i] = rows[row];
    }
  }

  // Update column start indices
  for (int i = col+1; i <= m_cols; ++i)
    m_colstart[i] += n_diff;

  // Debugging: show sparse matrix after insertion
  #if defined(G_DEBUG_SPARSE_INSERTION)
  cout << " Out Data: ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_data[i] << " ";
  cout << endl << " Out Row : ";
  for (int i = 0; i < m_elements; ++i)
    cout << m_rowinx[i] << " ";
  cout << endl << " Out Col : ";
  for (int i = 0; i < m_cols+1; ++i)
    cout << m_colstart[i] << " ";
  cout << endl;
  #endif

  // Return
  return;
}


/***************************************************************************
 *                        Get minimum matrix element                       *
 * ----------------------------------------------------------------------- *
 ***************************************************************************/
double GSparseMatrix::min() const
{
  // Initialise minimum with fill value
  double result = m_fill_val;

  // Search all elements for the smallest one
  for (int i = 0; i < m_elements; ++i) {
    if (m_data[i] < result)
      result = m_data[i];
  }

  // If minimum is > 0.0 and there are zero elements then set the minimum
  // to 0.0
  if ((result > 0.0) && (m_elements < (m_rows*m_cols)))
    result = 0.0;

  // Return result
  return result;
}


/***************************************************************************
 *                          Get maximum matrix element                     *
 * ----------------------------------------------------------------------- *
 ***************************************************************************/
double GSparseMatrix::max() const
{
  // Initialise maximum with fill value
  double result = m_fill_val;

  // Search all elements for the largest one
  for (int i = 0; i < m_elements; ++i) {
    if (m_data[i] > result)
      result = m_data[i];
  }

  // If maximum is < 0.0 and there are zero elements then set the maximum
  // to 0.0
  if ((result < 0.0) && (m_elements < (m_rows*m_cols)))
    result = 0.0;

  // Return result
  return result;
}


/***************************************************************************
 *                     Initialises matrix filling stack                    *
 * ----------------------------------------------------------------------- *
 * The matrix filling stack is used to allow for a fast column-wise        *
 * filling of a sparse matrix. Columns are successively appended to a      *
 * stack which is regularily flushed when it is full. This reduces memory  *
 * copies and movements and increases filling speed.                       *
 ***************************************************************************/
void GSparseMatrix::stack_init(int size, int entries)
{
    // Free exisiting stack
    free_stack_members();

    // Initialise stack members
    init_stack_members();
    m_stack_max_entries = (entries > 0) ? entries : m_cols;
    m_stack_size        = (size    > 0) ? size    : G_SPARSE_MATRIX_DEFAULT_STACK_SIZE;

    // Allocate stack memory. Raise an exception if allocation fails
    m_stack_colinx = new int[m_stack_max_entries];
    m_stack_start  = new int[m_stack_max_entries+1];
    m_stack_data   = new double[m_stack_size];
    m_stack_rowinx = new int[m_stack_size];
    m_stack_work   = new int[m_cols];
    m_stack_buffer = new double[m_cols];

    // Initialise next free stack location to the first stack element
    m_stack_start[0] = 0;

    // Return
    return;
}


/***************************************************************************
 *                Push a compressed array on the matrix stack              *
 * ----------------------------------------------------------------------- *
 * The method puts new data on the stack while assuring that each column   *
 * is present only once. If an already existing column is encountered      *
 * the data from the existing and new column are mixed and put into a new  *
 * entry one the stack; the old entry is signalled as obsolete.            *
 * On return the method indicates the number of elements in the input      *
 * array that have not been put onto the stack (due to memory limits).     *
 * This value can be either '0' (i.e. all elements have been put on the    *
 * stack) or 'number' (i.e. none of the elements have been put on the      *
 * stack). Columns are not partially put onto the stack.                   *
 ***************************************************************************/
int GSparseMatrix::stack_push_column(const double* values, const int* rows,
                                     int number, int col)
{
  // Initialise return value
  int remaining = number; 

  // Single loop for common exit point
  do {

    // If the array is empty there is nothing to do
    if (!values || !rows || (number < 1))
      continue;

    // If there is no stack or the stack can not hold the requested number of 
    // elements then report number of array elements to the caller
    if (m_stack_data == NULL || number > m_stack_size)
      continue;

    // Raise an exception if the column index is invalid
    #if defined(G_RANGE_CHECK)
    if (col >= m_cols)
      throw GException::out_of_range(G_STACK_PUSH, 0, col, m_rows, m_cols);
    #endif

    // Raise an exception if the index array seems incompatible with matrix 
    // dimensions
    if (rows[number-1] >= m_rows)
      throw GException::matrix_vector_mismatch(G_STACK_PUSH, rows[number-1], m_rows, m_cols);

    // Debug header
    #if defined(G_DEBUG_SPARSE_STACK_PUSH)
    cout << "GSparseMatrix::stack_push_column(v, i, n, col=" << col << ")" << endl;
    cout << " Data to push on stack ...:";
    for (int i = 0; i < number; ++i)
      cout << " " << values[i];
    cout << endl;
    cout << " Row indices of data .....:";
    for (int i = 0; i < number; ++i)
      cout << " " << rows[i];
    cout << endl;
    #endif

    // If the stack is full then flush it before pushing the array onto it.
    // There are 2 conditions that may fill the stack: all entries are
    // occupied or there is not enough space to hold more elements
    if ((m_stack_entries >= m_stack_max_entries) ||
        (number          >= (m_stack_size - m_stack_start[m_stack_entries])))
      stack_flush();

    // If the specified column is already on the stack then mix new column with
    // old one and invalidate old column (by setting its column index to -1).
    // Since we loop here over all stack entries we don't want to have too
    // many entries in the stack. So don't set the maximum number of stack
    // entries too large ...
    for (int entry = 0; entry < m_stack_entries; ++entry) {
      if (col == m_stack_colinx[entry]) {

        // Get start and stop indices of existing column in stack
        int i_start = m_stack_start[entry];
        int i_stop  = m_stack_start[entry+1];

        // Allocate variables to hold mixing results
        int num_1;    // Number of elements that are only in stack column
        int num_2;    // Number of elements that are only in new column
        int num_mix;  // Number of elements that are in both columns

        // Determine how many elements are requested to hold the combined
        // column
        mix_column_prepare(&(m_stack_rowinx[i_start]), i_stop-i_start,
                           rows, number, &num_1, &num_2, &num_mix);
        int num_request = num_1 + num_2 + num_mix;

        // If there is not enough space in the stack to hold the combined
        // column we flush the stack and exit the loop now. In this case the
        // new column is put as the first column in the empty (flushed stack)
        if (num_request >= (m_stack_size - m_stack_start[m_stack_entries])) {
          stack_flush();
          break;
        }

        // There is enough space, so combine both columns into a fresh one
        int inx = m_stack_start[m_stack_entries];
        int num_new;
        mix_column(&(m_stack_data[i_start]), &(m_stack_rowinx[i_start]), i_stop-i_start,
                   values, rows, number,
                   &(m_stack_data[inx]), &(m_stack_rowinx[inx]), &num_new);

        // Store entry information and initialise start of next entry
        m_stack_colinx[m_stack_entries] = col;           // Store column index for entry
        m_stack_entries++;                               // Increase the # of entries
        m_stack_start[m_stack_entries] = inx + num_new;  // Set start pointer for next entry

        // Invalidate old column
        m_stack_colinx[entry] = -1;

        // Fall through to end
        remaining = 0;
        break;

      } // endif: we found an existing column
    } // endfor: looped over all columns

    // If column has already been inserted then fall through ...
    if (remaining == 0)
      continue;

    // Otherwise, push the array on the stack
    int inx = m_stack_start[m_stack_entries];
    for (int i = 0; i < number; ++i) {
      m_stack_data[inx]   = values[i];
      m_stack_rowinx[inx] = rows[i];
      inx++;
    }

    // Store entry information and initialise start of next entry
    m_stack_colinx[m_stack_entries] = col;     // Store column index for entry
    m_stack_entries++;                         // Increase the # of entries
    m_stack_start[m_stack_entries] = inx;      // Set start pointer for next entry

    // Signal success
    remaining = 0;

  } while (0); // End of main do-loop

  // Debug: show stack information  
  #if defined(G_DEBUG_SPARSE_STACK_PUSH)
  cout << " Number of stack entries .: " << m_stack_entries << endl;
  cout << " Stack entry columns .....:";
  for (int i = 0; i < m_stack_entries; ++i)
    cout << " " << m_stack_colinx[i];
  cout << endl;
  cout << " Stack entry starts ......:";
  for (int i = 0; i < m_stack_entries; ++i)
    cout << " " << m_stack_start[i];
  cout << " (next at " << m_stack_start[m_stack_entries] << ")" << endl;
  cout << " Stack data ..............:";
  for (int i = 0; i < m_stack_start[m_stack_entries]; ++i)
    cout << " " << m_stack_data[i];
  cout << endl;
  cout << " Stack rows ..............:";
  for (int i = 0; i < m_stack_start[m_stack_entries]; ++i)
    cout << " " << m_stack_rowinx[i];
  cout << endl;
  #endif

  // Return remaining number of elements
  return remaining;
}


/***************************************************************************
 *                 Push a vector column on the matrix stack                *
 * ----------------------------------------------------------------------- *
 * This method is identical to the precedent one, but it takes a full      *
 * vector instead of a compressed array. Internal working arrays are used  *
 * to convert the full column vector in a compressed array and to hand it  *
 * over to the compressed array version.                                   *
 ***************************************************************************/
int GSparseMatrix::stack_push_column(const GVector& v, int col)
{
  // Initialise number of non-zero elements
  int non_zero = 0;

  // Compress vector in the buffer and set-up row index array
  for (int i = 0; i < v.size(); ++i) {
    if (v[i] != 0.0) {
      m_stack_buffer[non_zero] = v[i];
      m_stack_work[non_zero]   = i;
      non_zero++;
    }
  }

  // Hand over to compressed array method
  int remaining = stack_push_column(m_stack_buffer, m_stack_work, non_zero, col);

  // Return remaining number of elements
  return remaining;
}


/***************************************************************************
 *                              Flush matrix stack                         *
 * ----------------------------------------------------------------------- *
 * Adds the stack to the actual matrix. First, the total number of matrix  *
 * elements is determined. The new memory is allocated to hold all         *
 * elements. Finally, all elements are filled into a working array that is *
 * then compressed into the matrix.                                        *
 * ----------------------------------------------------------------------- *
 * NOTE: The present algorithm assumes that each column occurs only once   *
 * in the stack!                                                           *
 ***************************************************************************/
void GSparseMatrix::stack_flush(void)
{
  // Do nothing if there is no stack
  if (m_stack_data == NULL)
    return;

  // Fill pending value
  fill_pending();

  // Debug header
  #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
  cout << "GSparseMatrix::stack_flush" << endl;
  cout << " Number of stack entries .: " << m_stack_entries << endl;
  cout << " Number of stack elements : " << m_stack_start[m_stack_entries] << endl;
  cout << " Number of matrix elements: " << m_elements << endl;
  #endif

  // Use stack working array to flag all columns that exist already in the
  // matrix by 1 and all non-existing columns by 0
  for (int col = 0; col < m_cols; ++col) {
    if (m_colstart[col] < m_colstart[col+1])
      m_stack_work[col] = 1;
    else
      m_stack_work[col] = 0;
  }

  // Initialise some element counters
  int new_elements = 0;
  #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
  int num_matrix   = 0;    // Number of elements only in matrix
  int num_stack    = 0;    // Number of elements only on stack
  int num_both     = 0;    // Number of elements in matrix and on stack
  #endif

  // Loop over all stack entries and gather the number of elements that are
  // new with respect to the initial matrix. For each column set a flag with
  // the following meanings:
  //  -(entry+2): Column exists and is also found in stack=entry
  //  +(entry+2): Column exists in stack=entry only
  //           1: Column exists in matrix only
  //           0: Column does neither exist in matrix or stack  
  for (int entry = 0; entry < m_stack_entries; ++entry) {

    // Get column for actual entry
    int col = m_stack_colinx[entry];

    // Consider only valid entries
    if (col >= 0) {

      // If column exists already in matrix then determine total number
      // of additional elements
      if (m_stack_work[col] == 1) {

        // Flag that this column is a mixed column
        m_stack_work[col] = -(entry+2);

        // Setup index boundaries
        int i_start = m_colstart[col];
        int i_stop  = m_colstart[col+1];
        int k_start = m_stack_start[entry];
        int k_stop  = m_stack_start[entry+1];

        // Allocate output counters
        int num_1;
        int num_2;
        int num_mix;

        // Analyse column mixing
        mix_column_prepare(&(m_rowinx[i_start]), i_stop-i_start,
                           &(m_stack_rowinx[k_start]), k_stop-k_start,
                           &num_1, &num_2, &num_mix);

        // Update element counters
        new_elements += num_2;
        #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
        num_matrix   += num_1;
        num_stack    += num_2;
        num_both     += num_mix;
        #endif

      } // endif: column existed in the matrix

      // If column did not exists in the matrix then consider all elements
      // as new
      else {
        m_stack_work[col]  = (entry+2);
        new_elements      += (m_stack_start[entry+1] - m_stack_start[entry]);
      }
    } // endif: entry was valid
  } // endfor: looped over all entries
  int elements = m_elements + new_elements;

  // Dump number of elements in new matrix 
  #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
  cout << " New elements ............: " << new_elements << endl;
  #endif

    // Allocate memory for new matrix (always keep some elbow room)
    m_alloc = elements + m_mem_block;
    double* new_data   = new double[m_alloc];
    int*    new_rowinx = new int[m_alloc];

  // Fill new matrix. For this purpose we loop over all matrix columns
  // and perform the operation that was identified in the previous scan
  int index = 0;
  for (int col = 0; col < m_cols; ++col) {

    // If column does not exist then skip
    if (m_stack_work[col] == 0) {
      m_colstart[col] = index;
      continue;
    }

    // If column exists in the matrix but not in the stack we copy the
    // existing column into the new matrix
    if (m_stack_work[col] == 1) {
      for (int i = m_colstart[col]; i < m_colstart[col+1]; ++i) {
        new_data[index]   = m_data[i];
        new_rowinx[index] = m_rowinx[i];
        index++;
        #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
        num_matrix++;
        #endif
      }
    }

    // If column is new (i.e. it did not exist in the matrix before) we 
    // copy the stack into the new matrix
    else if (m_stack_work[col] > 1) {
      int entry = m_stack_work[col] - 2;
      for (int i = m_stack_start[entry]; i < m_stack_start[entry+1]; ++i) {
        new_data[index]   = m_stack_data[i];
        new_rowinx[index] = m_stack_rowinx[i];
        index++;
        #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
        num_stack++;
        #endif
      }
    }

    // If column exists in the matrix and in the stack then we have to mix both
    else {

      // Get stack entry for column mix
      int entry = -(m_stack_work[col] + 2);

      // Setup index boundaries
      int i_start = m_colstart[col];
      int i_stop  = m_colstart[col+1];
      int k_start = m_stack_start[entry];
      int k_stop  = m_stack_start[entry+1];

      // Allocate output counter
      int num;

      // Perform column mixing
      mix_column(&(m_data[i_start]), &(m_rowinx[i_start]), i_stop-i_start,
                 &(m_stack_data[k_start]), &(m_stack_rowinx[k_start]), k_stop-k_start,
                 &(new_data[index]), &(new_rowinx[index]), &num);

      // Increment element index
      index += num;

    } // endelse: column mixing required

    // Store actual index in column start array
    m_colstart[col] = index;

  } // endfor: looped over all columns

  // Dump number of elements in new matrix after addition
  #if defined(G_DEBUG_SPARSE_STACK_FLUSH)
  cout << " Added elements ..........: " << index << " (should be " << elements << ")" << endl;
  cout << " - Matrix only ...........: " << num_matrix << endl;
  cout << " - Stack only ............: " << num_stack << endl;
  cout << " - Matrix & Stack ........: " << num_both << endl;
  #endif

  // Correct columns start array
  for (int col = m_cols; col > 0; --col)
    m_colstart[col] = m_colstart[col-1];
  m_colstart[0] = 0;

  // Delete old matrix memory
  if (m_data   != NULL) delete [] m_data;
  if (m_rowinx != NULL) delete [] m_rowinx;

  // Update pointers to new memory and update element counter
  m_data     = new_data;
  m_rowinx   = new_rowinx;
  m_elements = elements;

  // Stack is empty now, so reset stack counters
  m_stack_entries  = 0;
  m_stack_start[0] = 0;

  // Return
  return;
}


/***************************************************************************
 *                             Destroy matrix stack                        *
 * ----------------------------------------------------------------------- *
 * Flush and destroy matrix stack                                          *
 ***************************************************************************/
void GSparseMatrix::stack_destroy(void)
{
  // Flush stack first
  stack_flush();

  // Free stack members
  free_stack_members();

  // Initialise stack (no entries)
  init_stack_members();

  // Return
  return;
}


/***************************************************************************
 *                       Compute sum of non-zero elements                  *
 * ----------------------------------------------------------------------- *
 ***************************************************************************/
double GSparseMatrix::sum() const
{
  // Initialise matrix sum with fill value
  double result = m_fill_val;

  // Add all elements
  for (int i = 0; i < m_elements; ++i)
    result += m_data[i];

  // Return result
  return result;
}


/*==========================================================================
 =                                                                         =
 =                      GSparseMatrix private methods                      =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Allocate matrix
 *
 * @param[in] rows Number of rows to be allocated.
 * @param[in] cols Number of columns to be allocated.
 * @param[in] elements Number of matrix elements to be physically allocated.
 *
 * This is the main constructor code that allocates and initialises memory
 * for matrix elements.
 ***************************************************************************/
void GSparseMatrix::constructor(int rows, int cols, int elements)
{
    // Continue only if matrix is not empty
    if (rows > 0 && cols > 0) {

        // Allocate column start array. This is the only array that we can
        // allocate at this time. The other arrays can only be allocated during
        // filling of the matrix
        m_colstart = new int[cols+1];

        // Store (logical) matrix size
        m_rows = rows;
        m_cols = cols;

        // Initialise column start indices to 0
        for (int col = 0; col <= m_cols; ++col)
            m_colstart[col] = 0;

        // Optionally allocate memory for matrix elements
        if (elements > 0)
            alloc_elements(0, elements);

    } // endif: matrix was not empty

    // Return
    return;
}


/***********************************************************************//**
 * @brief Initialise class mambers
 ***************************************************************************/
void GSparseMatrix::init_members(void)
{
    // Initialise sparse matrix members
    m_rowinx    = NULL;
    m_mem_block = G_SPARSE_MATRIX_DEFAULT_MEM_BLOCK;
    m_zero      = 0.0;
    m_fill_val  = 0.0;
    m_fill_row  = 0;
    m_fill_col  = 0;
    m_symbolic  = NULL;
    m_numeric   = NULL;

    // Initialise stack members
    init_stack_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] m Matrix to be copied.
 ***************************************************************************/
void GSparseMatrix::copy_members(const GSparseMatrix& m)
{
    // Copy GSparseMatrix members
    m_mem_block = m.m_mem_block;
    m_zero      = m.m_zero;
    m_fill_val  = m.m_fill_val;
    m_fill_row  = m.m_fill_row;
    m_fill_col  = m.m_fill_col;

    // Copy row indices if they exist
    if (m.m_rowinx != NULL && m.m_alloc > 0) {
        m_rowinx = new int[m.m_alloc];
        for (int i = 0; i < m.m_elements; ++i)
            m_rowinx[i] = m.m_rowinx[i];
    }

    // Copy symbolic decomposition if it exists
    if (m.m_symbolic != NULL) {
        GSparseSymbolic* symbolic = new GSparseSymbolic();
        *symbolic  = *((GSparseSymbolic*)m.m_symbolic);
        m_symbolic = (void*)symbolic;
    }

    // Copy numeric decomposition if it exists
    if (m.m_numeric != NULL) {
        GSparseNumeric* numeric = new GSparseNumeric();
        *numeric  = *((GSparseNumeric*)m.m_numeric);
        m_numeric = (void*)numeric;
    }

    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete class members
 ***************************************************************************/
void GSparseMatrix::free_members(void)
{
    // De-allocate only if memory has indeed been allocated
    if (m_numeric  != NULL) delete (GSparseNumeric*)m_numeric;
    if (m_symbolic != NULL) delete (GSparseSymbolic*)m_symbolic;
    if (m_rowinx   != NULL) delete [] m_rowinx;

    // Properly mark members as free
    m_rowinx   = NULL;
    m_symbolic = NULL;
    m_numeric  = NULL;

    // Free stack members
    free_stack_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Initialise fill stack
 *
 * The fill stack is used to fill the sparse matrix without any prior know-
 * ledge about the number of location of the non-zero matrix elements.
 * Values are first filled into the stack and flushed into the sparse
 * matrix once the stack is full.
 ***************************************************************************/
void GSparseMatrix::init_stack_members(void)
{
    // Initialise stack members
    m_stack_max_entries = 0;
    m_stack_size        = 0;
    m_stack_entries     = 0;
    m_stack_colinx      = NULL;
    m_stack_start       = NULL;
    m_stack_data        = NULL;
    m_stack_rowinx      = NULL;
    m_stack_work        = NULL;
    m_stack_buffer      = NULL;

    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete fill-stack class members
 *
 * Deletes all memory that has been allocated using the init_stack_members()
 * method.
 ***************************************************************************/
void GSparseMatrix::free_stack_members(void)
{
    // Free stack members
    if (m_stack_colinx != NULL) delete [] m_stack_colinx;
    if (m_stack_start  != NULL) delete [] m_stack_start;
    if (m_stack_data   != NULL) delete [] m_stack_data;
    if (m_stack_rowinx != NULL) delete [] m_stack_rowinx;
    if (m_stack_work   != NULL) delete [] m_stack_work;
    if (m_stack_buffer != NULL) delete [] m_stack_buffer;

    // Properly mark members as free
    m_stack_colinx = NULL;
    m_stack_start  = NULL;
    m_stack_data   = NULL;
    m_stack_rowinx = NULL;
    m_stack_work   = NULL;
    m_stack_buffer = NULL;

    // Return
    return;
}


/***************************************************************************
 *                   Determines element index for (row,col)                *
 * ----------------------------------------------------------------------- *
 * Returns the index in the compressed array for (row,col). The following  *
 * special results exist:                                                  *
 *         -1: Requested index does not exist in the matrix                *
 * m_elements: Requested index is the pending element                      *
 ***************************************************************************/
int GSparseMatrix::get_index(int row, int col) const
{
  // Initialise element to 'not found'
  int index = -1;

  // If we have a pending element then check if this element is requested
  if (m_fill_val != 0.0) {
    if (row == m_fill_row && col == m_fill_col)
      return m_elements;
  }

  // If requested element is not the pending element then check if it exists
  // in the matrix. Only if it is found its index is returned. Otherwise
  // the default index is -1, signalling that the element is absent.
  if (m_elements > 0) {
    int* ptr_colstart = m_colstart + col;
    int  i_start      = *ptr_colstart++;
    int  i_stop       = *ptr_colstart;
    int* ptr_rowinx   = m_rowinx + i_start;
    for (int i = i_start; i < i_stop; ++i) {
      int row_test = *ptr_rowinx++;
      if (row_test == row) {
        index = i;
        break;
      }
    }
  }

  // Return index
  return index;
}


/***************************************************************************
 *                       Fills pending matrix element                      *
 * ----------------------------------------------------------------------- *
 * If 'm_fill_val' is non-zero a pending matrix element exists that should *
 * be filled into (row,col)=(m_fill_row,m_fill_col). This routine performs *
 * the filling of the matrix with this element and resets 'm_fill_val' to  *
 * zero. This routine allows for element-by-element filling of a sparse    *
 * matrix. This is, of course, very time consuming and should in general   *
 * be avoided. However, it allows to design a sparse matrix class that     *
 * hides the matrix sparsity completely to the user.                       *
 ***************************************************************************/
void GSparseMatrix::fill_pending(void)
{
  // If we have a pending element then fill it into the matrix
  if (m_fill_val != 0.0) {

    // Debugging
    #if defined(G_DEBUG_SPARSE_PENDING) || defined(G_DEBUG_SPARSE_INSERTION)
    cout << "GSparseMatrix::fill_pending(): pending value " <<
         m_fill_val << " will be filled in location (" <<
         m_fill_row << "," << m_fill_col <<  ")" << endl;
    #endif

    // If there are so far no elements in the matrix then append element ...
    int inx_insert;
    if (m_elements == 0)
      inx_insert = 0;

    // ... otherwise search for index to insert
    else {
      int* ptr_colstart = m_colstart + m_fill_col;
      int  i_start      = *ptr_colstart++;
      int  i_stop       = *ptr_colstart;
      int* ptr_rowinx   = m_rowinx + i_start;
      for (inx_insert = i_start; inx_insert < i_stop; ++inx_insert) {
        int row_test = *ptr_rowinx++;
        if (row_test > m_fill_row) {
          break;
        }
      }
    }

    // Allocate memory for new element
    alloc_elements(inx_insert, 1);

    // Insert element
    m_data[inx_insert]   = m_fill_val;
    m_rowinx[inx_insert] = m_fill_row;

    // Update column start indices
    for (int col = m_fill_col+1; col <= m_cols; ++col)
      m_colstart[col] += 1;

    // Reset fill value
    m_fill_val = 0.0;
    m_fill_row = 0;
    m_fill_col = 0;

    // Debugging: show sparse matrix after filling
    #if defined(G_DEBUG_SPARSE_PENDING) || defined(G_DEBUG_SPARSE_INSERTION)
    cout << " Data: ";
    for (int i = 0; i < m_elements; ++i)
      cout << m_data[i] << " ";
    cout << endl << " Row.: ";
    for (int i = 0; i < m_elements; ++i)
      cout << m_rowinx[i] << " ";
    cout << endl << " Col.: ";
    for (int i = 0; i < m_cols+1; ++i)
      cout << m_colstart[i] << " ";
    cout << endl;
    #endif

  } // endif: a pending matrix element was found

}


/***************************************************************************
 *                  Allocate memory for new matrix elements                *
 * ----------------------------------------------------------------------- *
 * Inserts a memory allocation for 'num' elements at the index 'start'.    *
 * The new elements are filled with 0.0 and the corresponding row indices  *
 * are set to 0.                                                           *
 * NOTE: This routine does not take care of updating 'm_colstart'. This    *
 * has to be done by the client.                                           *
 ***************************************************************************/
void GSparseMatrix::alloc_elements(int start, int num)
{
  // Dump header
  #if defined(G_DEBUG_SPARSE_MALLOC)
  cout << "GSparseMatrix::alloc_elements(start=" << start << ", num=" << 
          num << ")" << endl;
  cout << " Before allocation : " << m_elements << " " << m_alloc << endl;
  #endif

  // Continue only if we need memory
  if (num > 0) {

    // If start is after the end then append memory
    if (start > m_elements)
      start = m_elements;

    // Determine the requested new logical size of the matrix
    int new_size = m_elements + num;

    // Case A: the requested memory is already available, so just move the
    // data to make space for new elements and initialise the new cells
    if (new_size <= m_alloc) {

      // Move up all elements after index to insert
      #if defined(G_USE_MEMMOVE)
      int n_copy = m_elements - start;
      memmove(&(m_data[start+num]), &(m_data[start]), sizeof(double)*n_copy);
      memmove(&(m_rowinx[start+num]), &(m_rowinx[start]), sizeof(long)*n_copy);
      #else
      for (int i = m_elements - 1; i >= start; --i) {
        m_data[i+num]   = m_data[i];
        m_rowinx[i+num] = m_rowinx[i];
      }
      #endif

      // Clear new elements (zero content for row 0)
      for (int i = start; i < start+num; ++i) {
        m_data[i]   = 0.0;
        m_rowinx[i] = 0;
      }

      // Update element counter
      m_elements += num;

    } // endif: Case A: memory already existed

    // Case B: more memory is needed, so allocate it, copy the existing
    // content, and initialise new cells
    else {

      // Make sure that enough memory is allocated
      int new_propose = m_alloc + m_mem_block;
      m_alloc = (new_size > new_propose) ? new_size : new_propose;

        // Allocate memory for new elements
        double* new_data   = new double[m_alloc];
        int*    new_rowinx = new int[m_alloc];

      // Copy all elements before index to insert
      #if defined(G_USE_MEMCPY)
      int n_copy = start;
      memcpy(new_data,   m_data,   sizeof(double)*n_copy);
      memcpy(new_rowinx, m_rowinx, sizeof(long)*n_copy);
      #else
      for (int i = 0; i < start; ++i) {
        new_data[i]   = m_data[i];
        new_rowinx[i] = m_rowinx[i];
      }
      #endif

      // Clear new elements (zero content for row 0)
      for (int i = start; i < start+num; ++i) {
        new_data[i]   = 0.0;
        new_rowinx[i] = 0;
      }

      // Copy all elements after index to insert
      #if defined(G_USE_MEMCPY)
      n_copy = m_elements - start;
      memcpy(&(new_data[start+num]),   &(m_data[start]),   sizeof(double)*n_copy);
      memcpy(&(new_rowinx[start+num]), &(m_rowinx[start]), sizeof(long)*n_copy);
      #else
      for (int i = start; i < m_elements; ++i) {
        new_data[i+num]   = m_data[i];
        new_rowinx[i+num] = m_rowinx[i];
      }
      #endif

      // Delete old memory
      if (m_data   != NULL) delete [] m_data;
      if (m_rowinx != NULL) delete [] m_rowinx;

      // Update pointers to new memory and update element counter
      m_data      = new_data;
      m_rowinx    = new_rowinx;
      m_elements += num;

    } // endelse: Case B: more memory was needed

  } // endif: needed new memory

  // Dump new memory size
  #if defined(G_DEBUG_SPARSE_MALLOC)
  cout << " After allocation .: " << m_elements << " " << m_alloc << endl;
  #endif

  // Return
  return;
}


/***************************************************************************
 *                  Free memory for obsolete matrix elements               *
 * ----------------------------------------------------------------------- *
 * Free memory for 'num' elements starting from index 'start'.             *
 * NOTE: This routine does not take care of updating 'm_colstart'. This    *
 * has to be done by the client.                                           *
 ***************************************************************************/
void GSparseMatrix::free_elements(int start, int num)
{
  // Dump header
  #if defined(G_DEBUG_SPARSE_MALLOC)
  cout << "GSparseMatrix::free_elements(start=" << start << ", num=" << 
          num << ")" << endl;
  #endif

  // Continue only if we need to free memory and if start is within the
  // range
  if (num > 0 && start < m_elements) {

    // Determine the requested new logical size of the matrix
    int new_size = m_elements - num;

    // If there are no elements then simply delete all matrix elements ...
    if (new_size < 1) {
      if (m_data   != NULL) delete [] m_data;
      if (m_rowinx != NULL) delete [] m_rowinx;
        m_data     = NULL;
        m_rowinx   = NULL;
        m_elements = 0;
        m_alloc    = 0;
     }

     // ... otherwise shrink the array
     else {

       // Case A: If at least one entire memory block has been liberated then 
       // physically shrink the matrix array
       if (m_alloc - new_size > m_mem_block) {

         // Shrink, but leave a memory block for possible future filling
         m_alloc = new_size + m_mem_block;

           // Allocate new memory
           double* new_data   = new double[m_alloc];
           int*    new_rowinx = new int[m_alloc];

         // Copy all elements before the starting index
         #if defined(G_USE_MEMCPY)
         int n_copy = start;
         memcpy(new_data,   m_data,   sizeof(double)*n_copy);
         memcpy(new_rowinx, m_rowinx, sizeof(long)*n_copy);
         #else
         for (int i = 0; i < start; ++i) {
           new_data[i]   = m_data[i];
           new_rowinx[i] = m_rowinx[i];
         }
         #endif

         // Copy all elements after the starting index
         #if defined(G_USE_MEMCPY)
         n_copy = new_size - start;
         memcpy(&(new_data[start]),   &(m_data[start+num]),   sizeof(double)*n_copy);
         memcpy(&(new_rowinx[start]), &(m_rowinx[start+num]), sizeof(long)*n_copy);
         #else
         for (int i = start; i < new_size; ++i) {
           new_data[i]   = m_data[i+num];
           new_rowinx[i] = m_rowinx[i+num];
         }
         #endif

        // Delete old memory
        if (m_data   != NULL) delete [] m_data;
        if (m_rowinx != NULL) delete [] m_rowinx;

        // Update pointers to new memory and update element counter
        m_data     = new_data;
        m_rowinx   = new_rowinx;
        m_elements = new_size;

      } // endif: Case A: memory shrinkage performed

      // Case B: we keep the memory and just move the elements
      else {

        // Move all elements after the starting index
        #if defined(G_USE_MEMMOVE)
        int n_copy = new_size - start;
        memmove(&(m_data[start]),   &(m_data[start+num]),   sizeof(double)*n_copy);
        memmove(&(m_rowinx[start]), &(m_rowinx[start+num]), sizeof(long)*n_copy);
        #else
        for (int i = start; i < new_size; ++i) {
          m_data[i]   = m_data[i+num];
          m_rowinx[i] = m_rowinx[i+num];
        }
        #endif

        // Update element counter
        m_elements = new_size;

      } // endelse: Case B

    } // endif: array shrinkage needed
  } // endif: needed new memory

  // Return
  return;
}


/***************************************************************************
 *                           remove_zero_row_col                           *
 * ----------------------------------------------------------------------- *
 * Remove all rows and columns that contain only zeros from matrix. This   *
 * function is needed for compressed matrix factorisation. The resulting   *
 * matrix has reduced size (# of rows and columns) and dimensions (# of    *
 * elements). Note that the physical memory is not reduced by the routine. *
 ***************************************************************************/
void GSparseMatrix::remove_zero_row_col(void)
{
  // Dump header
  #if defined(G_DEBUG_SPARSE_COMPRESSION)
  cout << "GSparseMatrix::remove_zero_row_col" << endl;
  #endif

  // Fill pending value in matrix
  fill_pending();

  // Select non-zero rows and columns of matrix
  select_non_zero();

  // Stop if there is no compression
  if (m_rows == m_num_rowsel && m_cols == m_num_colsel)
    return;

  // Raise exception if all matrix elements are zero
  if (m_num_rowsel < 1 || m_num_colsel < 1)
    throw GException::matrix_zero(G_REMOVE_ZERO);

    // Allocate row mapping array
    int* row_map = new int[m_rows];

  // Setup row mapping array that maps original matrix rows into compressed
  // matrix rows. An entry of -1 indicates that the row should be dropped
  for (int row = 0; row < m_rows; ++row)
    row_map[row] = -1;
  for (int c_row = 0; c_row < m_num_rowsel; ++c_row)
    row_map[m_rowsel[c_row]] = c_row;

  // Initialise pointers to compressed array
  double* d_data   = m_data;
  int*    d_rowinx = m_rowinx;

  // Initialise column start of first column to zero
  m_colstart[0] = 0;

  // Dump column start array
  #if defined(G_DEBUG_SPARSE_COMPRESSION)
  cout << " before compression (" << m_colstart[m_cols] << "):";
  for (int col = 0; col <= m_cols; ++col)
    cout << " " << m_colstart[col];
  cout << endl;
  #endif

  // Loop over all columns of compressed matrix
  for (int c_col = 0; c_col < m_num_colsel; ++c_col) {

    // Get index range for elements in original matrix
    int i_start = m_colstart[m_colsel[c_col]];
    int i_stop  = m_colstart[m_colsel[c_col]+1];

    // Initialise number of element counter for the compressed column
    int num = 0;

    // Loop over all elements in original column
    int c_row;
    for (int i = i_start; i < i_stop; ++i) {
      if ((c_row = row_map[m_rowinx[i]]) >= 0) {
        *d_data++   = m_data[i];
        *d_rowinx++ = c_row;
        num++;
      }
    }

    // Update column stop
    m_colstart[c_col+1] = m_colstart[c_col] + num;

  } // endfor: looped over all columns of compressed matrix

  // Dump column start array
  #if defined(G_DEBUG_SPARSE_COMPRESSION)
  cout << " after compression (" << m_colstart[m_num_colsel] << ") :";
  for (int c_col = 0; c_col <= m_num_colsel; ++c_col)
    cout << " " << m_colstart[c_col];
  cout << endl;
  #endif

  // Free row mapping array
  delete [] row_map;

  // Update matrix size
  m_rows = m_num_rowsel;
  m_cols = m_num_colsel;

  // Return
  return;
}


/***************************************************************************
 *                           insert_zero_row_col                           *
 * ----------------------------------------------------------------------- *
 * Insert zero rows and columns into matrix. Since for a sparse matrix     *
 * this does not require any allocation of additional memory, the data are *
 * not moved by this function, but the pointers are re-arranged.           *
 ***************************************************************************/
void GSparseMatrix::insert_zero_row_col(int rows, int cols)
{
  // Dump header
  #if defined(G_DEBUG_SPARSE_COMPRESSION)
  cout << "GSparseMatrix::insert_zero_row_col(" << rows << "," << cols << 
          ")" << endl;
  #endif

  // Fill pending value in matrix
  fill_pending();

  // Stop if there is no insertion
  if (m_rows == rows && m_cols == cols)
    return;

  // If row selection exists then restore row indices
  if (m_rowsel != NULL) {
    for (int i = 0; i < m_elements; ++i)
      m_rowinx[i] = m_rowsel[m_rowinx[i]];
  }

  // Dump column start array
  #if defined(G_DEBUG_SPARSE_COMPRESSION)
  cout << " before restoration (" << m_colstart[m_num_colsel] << "):";
  for (int c_col = 0; c_col <= m_num_colsel; ++c_col)
    cout << " " << m_colstart[c_col];
  cout << endl;
  #endif

  // If column selection exists then restore column counters
  if (m_colsel != NULL) {

    // Start insertion from the last original column
    int col_stop = cols - 1;

    // Loop over all compressed columns
    for (int c_col = m_num_colsel-1; c_col > 0; --c_col) {
      int col_start = m_colsel[c_col-1] + 1;
      int col_value = m_colstart[c_col];
      for (int col = col_start; col <= col_stop; ++col)
        m_colstart[col] = col_value;
      col_stop = col_start - 1;
    }

    // Set first columns if they are not yet set
    for (int col = 0; col <= col_stop; ++col)
      m_colstart[col] = 0;

    // Restore the number of elements
    m_colstart[cols] = m_elements;
  }

  // Dump column start array
  #if defined(G_DEBUG_SPARSE_COMPRESSION)
  cout << " after restoration (" << m_colstart[cols] << ") :";
  for (int col = 0; col <= cols; ++col)
    cout << " " << m_colstart[col];
  cout << endl;
  #endif

  // Update matrix size
  m_rows = rows;
  m_cols = cols;

  // Return
  return;
}


/***************************************************************************
 *                      Prepare mix of sparse columns                      *
 * ----------------------------------------------------------------------- *
 * Prepare the mix of two sparse matrix columns into a single one.         *
 * src1_row  : Row index array [0...src1_num-1] of first column            *
 * src1_num  : Number of elements in first column                          *
 * src2_row  : Row index array [0...src2_num-1] of second column           *
 * src2_num  : Number of elements in second column                         *
 * num_1     : Number of elements only found in column 1                   *
 * num_2     : Number of elements only found in column 2                   *
 * num_mix   : Number of elements found in both columns                    *
 ***************************************************************************/
void GSparseMatrix::mix_column_prepare(const int* src1_row, int src1_num,
                                       const int* src2_row, int src2_num,
                                       int* num_1, int* num_2, int* num_mix)
{
  // Initialise element counters
  *num_1   = 0;
  *num_2   = 0;
  *num_mix = 0;

  // Initialise indices and row indices of both columns
  int inx_1 = 0;                    // Column 1 element index
  int inx_2 = 0;                    // Column 2 element index
  int row_1 = src1_row[inx_1];      // Column 1 first row index
  int row_2 = src2_row[inx_2];      // Column 2 first row index

  // Mix elements of both columns while both contain still elements
  while (inx_1 < src1_num && inx_2 < src2_num) {

    // Case A: the element exist in both columns
    if (row_1 == row_2) {
      row_1 = src1_row[++inx_1];
      row_2 = src2_row[++inx_2];
      (*num_mix)++;
    }

    // Case B: the element exists only in first column
    else if (row_1 < row_2) {
      row_1 = src1_row[++inx_1];
      (*num_1)++;
    }

    // Case C: the element exists only in second column
    else {
      row_2 = src2_row[++inx_2];
      (*num_2)++;
    }

  } // endwhile: mixing

  // At this point either the first or the second column expired of elements
  // In the case that there are still elements remaining in the first column we
  // count them now ...
  if (inx_1 < src1_num)
    *num_1 += (src1_num - inx_1);

  // ... or in the case that there are still elements remaining in the second
  // column we count them now
  if (inx_2 < src2_num)
    *num_2 += (src2_num - inx_2);

  // We're done
  return;
}		


/***************************************************************************
 *                             Mix column                                  *
 * ----------------------------------------------------------------------- *
 * Mix two sparse matrix columns into one.                                 *
 * src1_data : Data array [0...src1_num-1] of first column                 *
 * src1_row  : Row index array [0...src1_num-1] of first column            *
 * src1_num  : Number of elements in first column                          *
 * src2_data : Data array [0...src2_num-1] of second column                *
 * src2_row  : Row index array [0...src2_num-1] of second column           *
 * src2_num  : Number of elements in second column                         *
 * dst_data  : Data array [0...dst_num-1] of result column                 *
 * dst_row   : Row index array [0...dst_num-1] of result column            *
 * dst_num   : Number of elements in result column                         *
 ***************************************************************************/
void GSparseMatrix::mix_column(const double* src1_data, const int* src1_row,
                               int src1_num,
                               const double* src2_data, const int* src2_row,
                               int src2_num,
                               double* dst_data, int* dst_row, int* dst_num)
{
  // Initialise indices and row indices of both columns
  int inx_1 = 0;                    // Column 1 element index
  int inx_2 = 0;                    // Column 2 element index
  int inx   = 0;                    // Result column element index
  int row_1 = src1_row[inx_1];
  int row_2 = src2_row[inx_2];

  // Mix elements of both columns while both contain still elements
  while (inx_1 < src1_num && inx_2 < src2_num) {

    // Case A: the element exists in both columns, so we add up the values
    if (row_1 == row_2) {
      dst_data[inx] = src1_data[inx_1] + src2_data[inx_2];
      dst_row[inx]  = row_1;
      row_1         = src1_row[++inx_1];
      row_2         = src2_row[++inx_2];
    }

    // Case B: the element exists only in first column, so we copy the element
    // from the first column
    else if (row_1 < row_2) {
      dst_data[inx] = src1_data[inx_1];
      dst_row[inx]  = row_1;
      row_1         = src1_row[++inx_1];
    }

    // Case C: the element exists only in second column, so we copy the element
    // from the second column
    else {
      dst_data[inx] = src2_data[inx_2];
      dst_row[inx]  = row_2;
      row_2         = src2_row[++inx_2];
    }

    // Update the destination index since we added a element
    inx++;

  } // endwhile: mixing

  // At this point either the first or the second column expired of elements
  // In the case that there are still elements remaining in the first column we
  // add them now ...
  for (int i = inx_1; i < src1_num; ++i, ++inx) {
    dst_data[inx] = src1_data[i];
    dst_row[inx]  = src1_row[i];
  }

  // ... or in the case that there are still elements remaining in the second
  // column we add them now
  for (int i = inx_2; i < src2_num; ++i, ++inx) {
    dst_data[inx] = src2_data[i];
    dst_row[inx]  = src2_row[i];
  }

  // Now store the number of columns in the second column
  *dst_num = inx;

  // We're done
  return;
}


/*==========================================================================
 =                                                                         =
 =                           GSparseMatrix friends                         =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Output operator
 *
 * @param[in] os Output stream.
 * @param[in] m Matrix to put in output stream.
 ***************************************************************************/
std::ostream& operator<< (std::ostream& os, const GSparseMatrix& m)
{
    // Determine number of elements
    int nonzero;
    int elements = m.m_elements;
    if (m.m_fill_val == 0.0) {
        nonzero  = (m.m_colstart != NULL) ? m.m_colstart[m.m_cols] : 0;
    }
    else {
        nonzero  = (m.m_colstart != NULL) ? m.m_colstart[m.m_cols]+1 : 0;
        elements++;
    }

    // Put header in stream
    os << "=== GSparseMatrix ===" << std::endl;
    if (m.m_rowsel != NULL) {
        os << " Number of rows ............: " << m.m_rows
           << " (compressed " << m.m_num_rowsel << ")" << std::endl;
    }
    else
        os << " Number of rows ............: " << m.m_rows << std::endl;
    if (m.m_colsel != NULL) {
        os << " Number of columns .........: " << m.m_cols
           << " (compressed " << m.m_num_colsel << ")" << std::endl;
    }
    else
        os << " Number of columns .........: " << m.m_cols << std::endl;
    os << " Number of non-zero elements: " << nonzero
       << " (" << elements << ")" << std::endl;
    if (m.m_fill_val != 0.0) {
        os << " Pending element ...........: (" << m.m_fill_row << ","
           << m.m_fill_col << ")=" << m.m_fill_val << std::endl;
    }
    os << " Number of allocated cells .: " << m.m_alloc << std::endl;
    os << " Memory block size .........: " << m.m_mem_block << std::endl;
    os << " Sparse matrix fill ........: " << m.fill() << std::endl;

    // If there is a symbolic decomposition then put it also in the stream
    if (m.m_symbolic != NULL)
        os << std::endl << *((GSparseSymbolic*)m.m_symbolic);

    // If there is a numeric decomposition then put it also in the stream
    if (m.m_numeric != NULL)
        os << std::endl << *((GSparseNumeric*)m.m_numeric);

    // Return output stream
    return os;
}


/***********************************************************************//**
 * @brief Return matrix with absolute values of all elements
 *
 * @param[in] m Matrix for which absolute values are to be returned.
 ***************************************************************************/
GSparseMatrix abs(const GSparseMatrix& m)
{
    // Define result matrix
    GSparseMatrix result = m;

    // Fill pending element
    result.fill_pending();

    // Convert all elements to absolute values
    for (int i = 0; i < result.m_elements; ++i)
        result.m_data[i] = std::abs(result.m_data[i]);

    // Return result
    return result;
}


/***************************************************************************
 *                                cs_symperm                               *
 * ----------------------------------------------------------------------- *
 * C = A(p,p) where A and C are symmetric the upper part stored.           *
 * ----------------------------------------------------------------------- *
 * Input:   A             Sparse matrix                                    *
 *          pinv          pinv[0..n-1]                                     *
 * Output:  C             Sparse matrix                                    *
 ***************************************************************************/
GSparseMatrix cs_symperm(const GSparseMatrix& m, const int* pinv)
{
    // Declare loop variables
    int i, j, p, q, i2, j2;

    // Assign matrix attributes
    int     n  = m.m_cols;
    int*    Ap = m.m_colstart;
    int*    Ai = m.m_rowinx; 
    double* Ax = m.m_data;

    // Allocate result matrix
    GSparseMatrix C(n, n, Ap[n]);

    // Allocate and initialise workspace
    int  wrk_size = n;
    int* wrk_int  = new int[wrk_size];
    for (i = 0; i < wrk_size; ++i)
        wrk_int[i] = 0;

    // Assign result matrix attributes
    int*    Cp = C.m_colstart;
    int*    Ci = C.m_rowinx; 
    double* Cx = C.m_data;

    // Count entries in each column of C
    for (j = 0; j < n; j++) {

        // Column j of A is column j2 of C
        j2 = pinv ? pinv[j] : j;

        // Loop over entries in column j
        for (p = Ap[j]; p < Ap[j+1]; p++) {
            i = Ai [p];
            if (i > j) continue;              // skip lower triangular part of A
            i2 = pinv ? pinv[i] : i;          // row i of A is row i2 of C
            wrk_int[G_MAX(i2, j2)]++;         // column count of C
        }
    }

    // Compute column pointers of C
    cs_cumsum(Cp, wrk_int, n);

    // Loop over all columns of A
    for (j = 0 ; j < n ; j++) {

        // Column j of A is column j2 of C
        j2 = pinv ? pinv[j] : j;

        // Loop over entries in column j
        for (p = Ap[j]; p < Ap[j+1]; p++) {
            i = Ai [p] ;
            if (i > j) continue;              // skip lower triangular part of A
            i2    = pinv ? pinv[i] : i;       // row i of A is row i2 of C
            Ci[q  = wrk_int[G_MAX(i2,j2)]++] = G_MIN(i2,j2);
            if (Cx) Cx[q] = Ax[p];
        }
    }

    // Free workspace
    delete [] wrk_int;
  
    // Rectify the number of elements in matrix C
    C.free_elements(Cp[n], (C.m_elements-Cp[n]));

    // Return result
    return C;

}


/***************************************************************************
 * @brief Compute transpose matrix
 *
 * @param[in] m     Matrix.
 * @param[in] value Flag that signals if values should be copied.
 *
 * The flag 'values' allows to avoid copying the actual data values. This
 * allows to perform a logical matrix transposition, as needed by the
 * symbolic matrix analysis class.
 *
 * Note that this method does not support pending elements (they have to be
 * filled before).
 ***************************************************************************/
GSparseMatrix cs_transpose(const GSparseMatrix& m, int values)
{
    // Declare and allocate result matrix 
    GSparseMatrix result(m.m_cols, m.m_rows, m.m_elements);

    // Allocate and initialise workspace
    int  wrk_size = m.m_rows;
    int* wrk_int  = new int[wrk_size];
    for (int i = 0; i < wrk_size; ++i) {
        wrk_int[i] = 0;
    }

    // Setup the number of non-zero elements in each row
    // for (p = 0 ; p < Ap [n] ; p++) w [Ai [p]]++ ;
    // Ap[n] = m.m_colstart[col]
    //     n = m.m_cols
    // Ai[p] = m.m_rowinx[p]
    for (int p = 0; p < m.m_colstart[m.m_cols]; ++p) {
        wrk_int[m.m_rowinx[p]]++;
    }

    // Set row pointers. To use a GSparseSymbolic function we have to
    // allocate and object (but this does not take memory)
    cs_cumsum(result.m_colstart, wrk_int, m.m_rows);

    // Case A: Normal transponse, including assignment of values
    if (values) {
        for (int col = 0; col < m.m_cols; ++col) {
            for (int p = m.m_colstart[col]; p < m.m_colstart[col+1] ; ++p) {
                int i              = wrk_int[m.m_rowinx[p]]++;
                result.m_rowinx[i] = col;
                result.m_data[i]   = m.m_data[p] ;
            }
        }
    }

    // Case B: Logical transponse, no assignment of values is performed
    else {
        for (int col = 0; col < m.m_cols; ++col) {
            for (int p = m.m_colstart[col]; p < m.m_colstart[col+1] ; ++p) {
                result.m_rowinx[wrk_int[m.m_rowinx[p]]++] = col;
            }
        }
    }
    
    // Free workspace
    delete [] wrk_int;

    // Return transponse matrix
    return result;

}


/*==========================================================================
 =                                                                         =
 =                            Other functions                              =
 =                                                                         =
 ==========================================================================*/

/***************************************************************************
 *                                  cs_cumsum                              *
 * ----------------------------------------------------------------------- *
 * Evaluate p[0..n] = cumulative sum of c[0..n-1]                          *
 * ----------------------------------------------------------------------- *
 * Input:   c[0..n-1]      integer array of n elements                     *
 * Output:  nz2            cumulative sum of c[0..n-1]                     *
 *          p[0..n]        integer array of n+1 elements                   *
 *          c[0..n-1]      holds p[0..n-1] on output                       *
 ***************************************************************************/
double cs_cumsum(int* p, int* c, int n)
{
    // Signal error if one of the input pointers is NULL
    if (!p || !c) return (-1);

    // Initialise sums (integer and double)
    int    nz  = 0;
    double nz2 = 0.0;

    // Evaluate p[0..n] = cumulative sum of c[0..n-1]
    for (int i = 0; i < n; ++i) {
        p[i]  = nz ;
        nz   += c[i];
        nz2  += c[i];    // also in double to avoid int overflow
        c[i]  = p[i];    // also copy p[0..n-1] back into c[0..n-1]
    }
    p[n] = nz ;

    // Return cumulative sum of c[0..n-1]
    return nz2;
}