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
#![doc="Provides the basic Matrix data type
"]

// std imports
use std::mem;
use std::ptr;
use std::ops;
use std::cmp;
use std::fmt;
use num::{Float};
use std::iter::Iterator;
use std::rt::heap::{allocate, deallocate};
use std::ops::{Index};
use std::raw::Slice;

// external imports
use num::traits::{Zero, One, Signed};
use num::complex::{Complex32, Complex64};

// local imports

use discrete::{mod_n};
use algebra::structure::{MagmaBase, 
    CommutativeMonoidAddPartial, 
    CommutativeMonoidMulPartial,
    QuasiGroupAddPartial,
    CommutativeGroupAddPartial,
    FieldPartial};
use error::SRError;
use matrix::iter::*;
use matrix::view::MatrixView;
use matrix::traits::{Shape, NumberMatrix,
    Strided,
    StridedNumberMatrix,
    StridedFloatMatrix,
    Introspection, 
    MatrixBuffer,
    Search};


use util;


#[doc = "
Represents a matrix of numbers.


The numbers are stored in column-major order.
This is the standard in Fortran and MATLAB.

"]
pub struct Matrix<T:MagmaBase> {
    /// Number of rows in the matrix
    rows : usize,
    /// Number of columns in the matrix
    cols : usize, 
    /// The pointer to raw data array of the matrix
    ptr : *mut T
}

/// A matrix of 8-bit signed integers
pub type MatrixI8 = Matrix<i8>;
/// A matrix of 16-bit signed integers
pub type MatrixI16 = Matrix<i16>;
/// A matrix of 32-bit signed integers
pub type MatrixI32 = Matrix<i32>;
/// A matrix of 64-bit signed integers
pub type MatrixI64 = Matrix<i64>;
/// A matrix of 8-bit unsigned integers
pub type MatrixU8 = Matrix<u8>;
/// A matrix of 16-bit unsigned integers
pub type MatrixU16 = Matrix<u16>;
/// A matrix of 32-bit unsigned integers
pub type MatrixU32 = Matrix<u32>;
/// A matrix of 64-bit unsigned integers
pub type MatrixU64 = Matrix<u64>;
/// A matrix of 32-bit floating point numbers.
pub type MatrixF32 = Matrix<f32>;
/// A matrix of 64-bit floating point numbers.
pub type MatrixF64 = Matrix<f64>;
/// A matrix of 32-bit complex numbers numbers.
pub type MatrixC32 = Matrix<Complex32>;
/// A matrix of 64-bit complex numbers numbers.
pub type MatrixC64 = Matrix<Complex64>;




/// Static functions for creating  a matrix
impl<T:MagmaBase> Matrix<T> {

#[doc = "Constructs a new matrix of given size (uninitialized).

# Remarks 

The contents of the matrix are not initialized. Hence, 
it doesn't make sense to use this function liberally.
Still the function is internally useful since
different constructor functions need to initialize
the matrix differently.
"]
    pub fn new(rows: usize, cols : usize)-> Matrix<T> {
        debug_assert! (mem::size_of::<T>() != 0);
        let capacity = rows *  cols;

        // Support for empty  matrices
        if capacity == 0{
            // We do not allocate any memory for the buffer.
            // We leave it as a NULL pointer.
            return Matrix { rows : rows, 
                cols : cols,
                ptr : ptr::null_mut()
            };
        }
        let bytes = capacity * mem::size_of::<T>();
        let raw = unsafe {
            allocate(bytes, mem::align_of::<T>())
        };
        let ptr = raw as *mut T;
        Matrix { rows : rows, 
                cols : cols, 
                ptr : ptr}
    }

}

/// Static functions for creating  a matrix of numbers
impl<T:CommutativeMonoidAddPartial> Matrix<T> {
    /// Constructs a scalar matrix
    pub fn from_scalar (scalar : T) -> Matrix <T>{
        let m : Matrix<T> = Matrix::new(1, 1);
        unsafe {*m.ptr = scalar;}
        m
    }

    /// Constructs a matrix of all zeros
    pub fn zeros(rows: usize, cols : usize)-> Matrix<T> {
        let m : Matrix<T> = Matrix::new(rows, cols);
        let ptr = m.ptr;
        // zero out the memory
        let z : T = Zero::zero();
        unsafe {
            for c in 0..cols{
                for r in 0..rows{
                    let offset = m.cell_to_offset(r, c);
                    let p  = ptr.offset(offset as isize);
                    *p = z;
                }
            } 
        }
        m
    }

    #[doc = "Constructs a matrix from a slice of data reading
    data in column wise order.
    "]
    pub fn from_slice_cw(rows: usize, cols : usize, values: &[T]) -> Matrix<T>{
        let mut mat : Matrix<T> = Matrix::new(rows, cols);
        // stride of new matrix
        let stride = mat.stride();
        // get a mutable slice from m
        {
            let dst_slice = mat.as_mut_slice();
            // The number of entries we can copy
            let n_values = values.len();
            let z : T = Zero::zero();
            let mut n = 0;
            let mut offset_dst = 0;
            for _ in 0..cols{
                for r in 0..rows{
                    let v = if n < n_values {
                        values[n]
                    }else{
                        z
                    };
                    dst_slice[offset_dst + r] = v;
                    n+=1;
                }
                offset_dst += stride;
            }
        }
        // return
        mat
    }

    #[doc = "Constructs a matrix from a slice of data reading data in row wise order.

# Remarks 

In source code, when we are constructing matrices from slices, a
slice looks easier to read in row wise order. Thus, this
function should be more useful in constructing matrices
by hand.
"]
    pub fn from_slice_rw(rows: usize, cols : usize, values: &[T]) -> Matrix<T>{
        let mat : Matrix<T> = Matrix::new(rows, cols);
        // get a mutable slice from m
        {
            let ptr = mat.ptr;
            // The number of entries we can copy
            let n_values = values.len();
            let z : T = Zero::zero();
            let mut n = 0;
            for r in 0..rows{
                for c in 0..cols{
                    let v = if n < n_values {
                        values[n]
                    }else{
                        z
                    };
                    let dst_offset = mat.cell_to_offset(r,c);
                    unsafe{
                        *ptr.offset(dst_offset) = v;
                    }
                    n+=1;
                }
            }
        }
        // return
        mat
    }

    pub fn from_iter_cw< A : Iterator<Item=T>>(rows: usize, cols : usize, mut iter: A) -> Matrix<T>{
        let mut mat : Matrix<T> = Matrix::new(rows, cols);
        let stride = mat.stride();
        // get a mutable slice from m
        {
            let dst_slice = mat.as_mut_slice();
            let mut offset_dst = 0;
            let z : T = Zero::zero();
            let mut completed_columns  = 0;
            'outer: for _ in 0..cols{
                for r in 0..rows{
                    let next_val = iter.next();
                    match next_val{
                        Some(val) => dst_slice[offset_dst + r] = val,
                        None => {
                            // Finish this column with zeros
                            for _ in r..rows{
                                dst_slice[offset_dst + r] = z;
                            }
                            completed_columns += 1;
                            offset_dst += stride;
                            break 'outer
                        }
                    };
                }
                completed_columns += 1;
                offset_dst += stride;
            }
            if completed_columns < cols {
                // We  need to fill remaining columns with zeros
                for _ in completed_columns..cols{
                    for r in 0..rows{
                        dst_slice[offset_dst + r] = z;
                    }
                    completed_columns += 1;
                    offset_dst += stride;
                }
            }
        }
        // return
        mat
    }


    /// Builds a matrix from an iterator reading numbers in a 
    /// row-wise order
    pub fn from_iter_rw< A : Iterator<Item=T>>(rows: usize, cols : usize, 
        iter: A) -> Matrix<T>{
        let m : Matrix<T> = Matrix::new(rows, cols);
        let ptr = m.ptr;
        let z : T = Zero::zero();
        let mut r = 0;
        let mut c = 0;
        let nc = m.num_cols();
        let nr = m.num_rows();
        for v in iter {
            if c == nc {
                c = 0;
                r = r + 1;
            }
            if r == nr {
                break;
            }
            let dst_offset = m.cell_to_offset(r, c);
            unsafe{
                *ptr.offset(dst_offset) = v;
            }
            c += 1;
        }
        loop {
            if c == nc {
                c = 0;
                r = r + 1;
            }
            if r == nr {
                break;
            }
            let dst_offset = m.cell_to_offset(r, c);
            unsafe{
                *ptr.offset(dst_offset) = z;
            }
            c += 1;
        }
        // return
        m
    }

    /// Construct a diagonal matrix from a vector
    pub fn diag_from_vec(v : &Matrix<T>) -> Matrix<T>{
        if !v.is_vector(){
            panic!(SRError::IsNotAVector.to_string());
        }
        let n = v.num_cells();
        let m : Matrix<T> = Matrix::zeros(n, n);
        let src = v.ptr;
        let dst = m.ptr;
        // Copy the elements of v in the vector
        for r in 0..n{
            let offset = m.cell_to_offset(r, r);
            unsafe{
                *dst.offset(offset) =  *src.offset(r as isize);
            }
        }
        m
    }

}

/// Static functions for creating  a matrix of numbers
impl<T:CommutativeMonoidAddPartial+One> Matrix<T> {

    /// Constructs a matrix of all ones.
    pub fn ones(rows: usize, cols : usize)-> Matrix<T> {
        let m : Matrix<T> = Matrix::new(rows, cols);
        // fill with ones
        let ptr = m.ptr;
        let o : T = One::one();
        unsafe {
            for c in 0..cols{
                for r in 0..rows{
                    let offset = m.cell_to_offset(r, c);
                    let p  = ptr.offset(offset as isize);
                    *p = o;
                }
            } 
        }
        m
    }


    /// Constructs an identity matrix
    pub fn identity(rows: usize, cols : usize) -> Matrix<T> {
        let m : Matrix<T> = Matrix::zeros(rows, cols);
        // fill with ones
        let ptr = m.ptr;
        let one : T = One::one();
        let n = cmp::min(rows, cols);
        for i in 0..n{
            let offset = m.cell_to_offset(i, i);
            unsafe{
                *ptr.offset(offset) = one;
            }
        }
        m
    }

    /// Constructs a unit vector
    /// (1, 0, 0), (0, 1, 0), (0, 0, 1), etc.
    pub fn unit_vector( length : usize, dim : usize) -> Matrix<T> {
        let mut m : Matrix<T> = Matrix::zeros(length, 1);
        m.set(dim, 0, One::one());
        m
    }

}


/// Core methods for all matrix types
impl<T:MagmaBase> Shape<T> for Matrix<T> {

    /// Returns the number of rows in the matrix
    fn num_rows(&self) -> usize {
        self.rows
    }

    /// Returns the number of columns in the matrix
    fn num_cols(&self) -> usize {
        self.cols
    }

    /// Returns the size of matrix in an (r, c) tuple
    fn size (&self)-> (usize, usize){
        (self.rows, self.cols)
    }

    /// Returns the number of cells in matrix
    fn num_cells(&self)->usize {
        self.rows * self.cols
    }


    unsafe fn get_unchecked(&self, r : usize, c : usize) -> T  {
        // These assertions help in checking matrix boundaries
        debug_assert!(r < self.rows);
        debug_assert!(c < self.cols);
        let offset = self.cell_to_offset(r, c);
        let v = self.ptr.offset(offset);
        // TODO : Optimize this
        v.as_ref().unwrap().clone()
    }

    fn set(&mut self, r : usize, c : usize, value : T) {
        // These assertions help in checking matrix boundaries
        debug_assert!(r < self.rows);
        debug_assert!(c < self.cols);
        unsafe {
            *self.ptr.offset(self.cell_to_offset(r, c)) = value;
        }
    }
}

/// Methods available to number matrices
impl<T:CommutativeMonoidAddPartial+CommutativeMonoidMulPartial> NumberMatrix<T> for Matrix<T> {

    /// Returns if the matrix is an identity matrix
    fn is_identity(&self) -> bool {
        let o : T = One::one();
        let z  : T = Zero::zero();
        let ptr = self.ptr;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let offset = self.cell_to_offset(r, c);
                let v = unsafe {*ptr.offset(offset)};
                if r == c {
                    if v != o {
                        return false;
                    }
                }else if v != z {
                    return false;
                }

            }
        } 
        true
    }

    /// Returns if the matrix is a diagonal matrix
    fn is_diagonal(&self) -> bool {
        let z  : T = Zero::zero();
        let ptr = self.ptr;
        for c in 0..self.cols{
            for r in 0..self.rows{
                if r != c {
                    let offset = self.cell_to_offset(r, c);
                    let v = unsafe {*ptr.offset(offset)};
                    if v != z {
                        return false;
                    }
                }
            }
        } 
        true
    }

    /// Returns if the matrix is lower triangular 
    fn is_lt(&self) -> bool {
        let z  : T = Zero::zero();
        let ptr = self.ptr;
        for c in 0..self.cols{
            for r in 0..c{
                let offset = self.cell_to_offset(r, c);
                let v = unsafe {*ptr.offset(offset)};
                if v != z {
                    return false;
                }
            }
        } 
        true
    }

    /// Returns if the matrix is upper triangular 
    fn is_ut(&self) -> bool {
        let z  : T = Zero::zero();
        let ptr = self.ptr;
        for c in 0..self.cols{
            for r in c+1..self.rows{
                let offset = self.cell_to_offset(r, c);
                let v = unsafe {*ptr.offset(offset)};
                if v != z {
                    return false;
                }
            }
        } 
        true
    }

    /// Returns if the matrix is symmetric
    fn is_symmetric(&self) -> bool{
        if !self.is_square(){
            // Only square matrices can be symmetric
            return false;
        }
        // size of the square matrix
        let n = self.num_rows();
        for i in 0..n{
            for j in (i + 1)..n{
                unsafe {
                    if self.get_unchecked(i, j) != self.get_unchecked(j, i) {
                        return false;
                    }
                }
            }
        }
        true
    }

    /// Returns the trace of the matrix
    fn trace(&self) -> T{
        let mut result: T = Zero::zero();
        for e in self.diagonal_iter(){
            result = result + e;
        }
        result
    }
}


/// Introspection support
impl<T> Introspection for Matrix<T> {
    /// This is a standard matrix object
    fn is_standard_matrix_type(&self) -> bool {
        true
    }
}

/// Strided buffer
impl<T:MagmaBase> Strided for Matrix<T> {

    /// Returns the number of actual memory elements 
    /// per column stored in the memory
    fn stride (&self)->usize {
        self.rows
    }

}

impl<T:FieldPartial> StridedNumberMatrix<T> for Matrix<T> {
}

impl<T:FieldPartial+Float> StridedFloatMatrix<T> for Matrix<T> {
}



/// Buffer access
impl<T:MagmaBase> MatrixBuffer<T> for Matrix<T> {

    /// Returns an unsafe pointer to the matrix's 
    /// buffer.
    #[inline]
    fn as_ptr(&self)-> *const T{
        self.ptr as *const T
    }

    /// Returns a mutable unsafe pointer to
    /// the matrix's underlying buffer
    #[inline]
    fn as_mut_ptr(&mut self) -> *mut T{
        self.ptr
    }

    /// Maps a cell index to actual offset in the internal buffer
    #[inline]
    fn cell_to_offset(&self, r : usize,  c: usize)-> isize {
        (c * self.stride() + r) as isize
    } 

}

/// Main methods of a matrix
impl<T:MagmaBase> Matrix<T> {

    /// Returns the capacity of the matrix 
    /// i.e. the number of elements it can hold
    pub fn capacity(&self)-> usize {
        self.rows * self.cols
    }

    /// Reshapes the matrix
    pub fn reshape(&mut self, rows: usize, cols : usize) -> bool {
        let new_capacity = rows * cols;
        if new_capacity != self.capacity(){
            false
        }
        else{
            // Reshape the matrix
            self.rows = rows;
            self.cols = cols;
            true
        }
    }

}



use std::fmt::Debug;

/// Functions to access matrix elements safely and without bounds checking.
impl<T: Debug + Clone + Copy + PartialEq> Matrix<T> {

    /// Returns an iterator over a specific row of matrix
    pub fn row_iter(&self, r : isize) -> RowIterator<T>{
        let r = mod_n(r, self.rows as isize);        
        // Lets find the offset of the begging of the row
        let offset = self.cell_to_offset(r, 0);
        let iter : RowIterator<T> = RowIterator::new(self.cols,
            self.stride(), unsafe {self.ptr.offset(offset)} as *const T);
        iter
    }

    /// Returns an iterator over a specific column of the matrix
    pub fn col_iter(&self, c : isize) -> ColIterator<T>{
        let c = mod_n(c, self.cols as isize);        
        // Lets find the offset of the begging of the column
        let offset = self.cell_to_offset(0, c);
        let iter : ColIterator<T> = ColIterator::new(self.rows,
            unsafe {self.ptr.offset(offset)} as *const T);
        iter
    }

    /// Returns an iterator over all cells  of the matrix
    pub fn cell_iter(&self) -> CellIterator<T>{
        let iter : CellIterator<T> = CellIterator::new(
            self.rows, self.cols, self.stride(),
            self.ptr as *const T);
        iter
    }

    /// Provide the main diagonal elements
    pub fn diagonal_iter(&self) -> DiagIterator<T>{
        DiagIterator::new(self.smaller_dim(),self.stride(), self.ptr)
    }
}

/// Functions to construct new matrices out of a matrix and other conversions
impl<T:CommutativeMonoidAddPartial+One> Matrix<T> {

    // Repeats this matrix in both horizontal and vertical directions 
    pub fn repeat_matrix(&self, num_rows : usize, num_cols : usize) -> Matrix<T> {
        let rows = self.rows * num_rows;
        let cols = self.cols * num_cols;
        let result : Matrix<T> = Matrix::new(rows, cols);
        let pd = result.ptr;
        let ps = self.ptr;
        for bc in 0..num_cols{
            let bc_start = bc * self.cols;
            for br in 0..num_rows{
                let br_start =  br * self.rows;
                for c in 0..self.cols {
                    for r in 0..self.rows{
                        let src_offset = self.cell_to_offset(r, c);
                        let dst_offset = result.cell_to_offset(br_start + r, bc_start + c);
                        unsafe{
                            *pd.offset(dst_offset) = *ps.offset(src_offset);
                        }
                    }
                }

            }
        }
        result
    }

    /// Extracts the primary diagonal from the matrix as a vector
    pub fn diagonal_vector(&self) -> Matrix<T> {
        let m  = self.smaller_dim();
        let result : Matrix<T> = Matrix::new(m, 1);
        let dst = result.ptr;
        for (i, e) in (0..m).zip(self.diagonal_iter()){
            unsafe{
                *dst.offset(i as isize) = e;
            } 
        }
        result        
    }

    /// Extracts the primary diagonal from the matrix as a matrix of same size
    pub fn diagonal_matrix(&self) -> Matrix<T> {
        let m  = cmp::min(self.rows, self.cols);
        let result : Matrix<T> = Matrix::zeros(self.rows, self.cols);
        let src = self.ptr;
        let dst = result.ptr;
        for i in 0..m{
            let offset = self.cell_to_offset(i, i);
            unsafe{
                *dst.offset(offset) = *src.offset(offset);
            } 
        }
        result        
    }

    /// Returns the upper triangular part of the matrix as a new matrix
    pub fn ut(&self)->Matrix<T>{
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let src = self.ptr;
        let dst = result.ptr;
        let z  : T = Zero::zero();
        for c in 0..self.cols{
            for r in 0..(c+1){
                let offset = self.cell_to_offset(r, c);
                unsafe {*dst.offset(offset) = *src.offset(offset);}
            }
            for r in (c+1)..self.rows{
                let offset = self.cell_to_offset(r, c);
                unsafe {*dst.offset(offset) = z;}
            }
        }
        result
    }

    /// Returns the lower triangular part of the matrix as a new matrix
    pub fn lt(&self)->Matrix<T>{
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let src = self.ptr;
        let dst = result.ptr;
        let z  : T = Zero::zero();
        for c in 0..self.cols{
            for r in 0..c{
                let offset = self.cell_to_offset(r, c);
                unsafe {*dst.offset(offset) = z;}
            }
            for r in c..self.rows{
                let offset = self.cell_to_offset(r, c);
                unsafe {*dst.offset(offset) = *src.offset(offset);}
            }
        }
        result
    }

    /// Returns the matrix with permuted rows
    pub fn permuted_rows(&self, permutation : &MatrixU16)->Matrix<T>{
        debug_assert!(permutation.is_col());
        debug_assert_eq!(permutation.num_cells(), self.num_rows());
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let src = self.ptr;
        let dst = result.ptr;
        for c in 0..self.cols{
            let src_start = self.cell_to_offset(0, c);
            let dst_start = result.cell_to_offset(0, c);
            for r in 0..self.num_rows(){
                let src_offset = src_start + permutation[r] as isize;
                let dst_offset = dst_start +  r as isize;
                unsafe {*dst.offset(dst_offset) = *src.offset(src_offset);}
            }
        }
        result
    }

    /// Returns the matrix with permuted columns
    pub fn permuted_cols(&self, permutation : &MatrixU16)->Matrix<T>{
        debug_assert!(permutation.is_col());
        debug_assert_eq!(permutation.num_cells(), self.num_cols());
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let src = self.ptr;
        let dst = result.ptr;
        for c in 0..self.cols{
            debug_assert!((permutation[c] as usize) < self.num_cols());
            let mut src_offset = self.cell_to_offset(0, permutation[c] as usize);
            let mut dst_offset = result.cell_to_offset(0, c);
            for _ in 0..self.num_rows(){
                unsafe {*dst.offset(dst_offset) = *src.offset(src_offset);}
                src_offset += 1;
                dst_offset += 1;
            }
        }
        result
    }

}

impl<T:CommutativeMonoidAddPartial+CommutativeMonoidMulPartial> Matrix<T> {
    /// Computes power of a matrix
    /// Returns a new matrix
    pub fn pow(&self, exp : usize) -> Matrix<T>{
        if !self.is_square() {
            panic!(SRError::IsNotSquareMatrix.to_string());
        }
        if exp == 0 {
            return Matrix::identity(self.rows, self.cols);
        }
        let mut result = self.clone();
        for _ in 0..(exp -1){
            result = &result * self;
        }
        result
    }




    /// Inner product or dot product of two vectors
    /// Both must be column vectors
    /// Both must have same length
    /// result = a' * b.
    pub fn inner_prod(&self, other : &Matrix<T>) -> T {
        debug_assert!(self.is_col());
        debug_assert!(other.is_col());
        debug_assert!(self.num_cells() == other.num_cells());
        let mut result : T =  Zero::zero();
        let pa = self.ptr;
        let pb = other.ptr;
        for i in 0..self.num_rows(){
            let ii = i as isize;
            let va = unsafe{*pa.offset(ii)};
            let vb = unsafe{*pb.offset(ii)};
            result = result + va * vb;
        }
        result
    }

    /// Outer product of two vectors
    /// Both must be column vectors
    /// Both must have same length
    /// result = a * b'.
    pub fn outer_prod(&self, other : &Matrix<T>) -> Matrix<T> {
        debug_assert!(self.is_col());
        debug_assert!(other.is_col());
        debug_assert!(self.num_cells() == other.num_cells());
        let n = self.num_rows();
        let result : Matrix<T> =  Matrix::new(n, n);
        let pa = self.ptr;
        let pb = other.ptr;
        let pc = result.ptr;
        for r in 0..n{
            for c in 0..n{
                let va = unsafe{*pa.offset(r as isize)};
                let vb = unsafe{*pb.offset(c as isize)};
                let offset = result.cell_to_offset(r, c);
                unsafe{
                    *pc.offset(offset) = va * vb;
                }
            }
        }
        result
    }

}

//+Neg<Output=T>
impl<T:CommutativeGroupAddPartial> Matrix<T> {
    /// Computes the unary minus of a matrix
    pub fn unary_minus(&self)-> Matrix<T> {
        let result : Matrix<T> = Matrix::new(self.cols, self.rows);
        let pa = self.ptr;
        let pc = result.ptr;
        for r in 0..self.rows{
            for c in 0..self.cols{
                let offset = self.cell_to_offset(r, c);
                unsafe {
                    *pc.offset(offset) = -*pa.offset(offset);
                }
            }
        }
        result
    }
}


/// These methods modify the matrix itself
impl<T:MagmaBase> Matrix<T> {

    /// Appends one or more columns at the end of matrix
    pub fn append_columns(&mut self, 
        other : &Matrix<T>
        )-> &mut Matrix<T> {
        let cols = self.cols;
        self.insert_columns(cols, other)
    }

    /// Prepends one or more columns at the beginning of matrix
    pub fn prepend_columns(&mut self,
        other : &Matrix<T> 
        )-> &mut Matrix<T> {
        self.insert_columns(0, other)
    }

    /// Inserts columns at the specified location
    pub fn insert_columns(&mut self,
        index  : usize,
        other : &Matrix<T> 
        )-> &mut Matrix<T> {
        debug_assert_eq!(self.num_rows() , other.num_rows());
        debug_assert!(other.num_cols() > 0);

        // check the capacity.
        let new_cols = self.cols + other.cols;
        let rows = self.rows;
        // We need to reallocate memory.
        self.reallocate(rows, new_cols);
        // Now create space for other matrix to be fitted in
        self.create_column_space(index, other.num_cols());
        // Finally copy the column data from the matrix.
        let src_ptr = other.ptr;
        let dst_ptr = self.ptr;
        for i in 0..other.num_cols(){
            let src_offset = other.cell_to_offset(0, i);
            let dst_offset = self.cell_to_offset(0, i + index);
            for j in 0..self.rows{
                let jj = j as isize;
                unsafe {
                    *dst_ptr.offset(dst_offset + jj) = *src_ptr.offset(src_offset + jj);
                }
            }
        }
        self
    }


    /// Appends one or more rows at the bottom of matrix
    pub fn append_rows(&mut self, 
        other : &Matrix<T>
        )-> &mut Matrix<T> {
        let rows = self.rows;
        self.insert_rows(rows, other)
    }

    /// Prepends one or more rows at the top of matrix
    pub fn prepend_rows(&mut self,
        other : &Matrix<T> 
        )-> &mut Matrix<T> {
        self.insert_rows(0, other)
    }

    /// Inserts rows at the specified location
    pub fn insert_rows(&mut self,
        index  : usize,
        other : &Matrix<T> 
        )-> &mut Matrix<T> {
        // Make sure that the dimensions are compatible.
        debug_assert_eq!(self.num_cols() , other.num_cols());
        // Make sure that there is data to be added.
        debug_assert!(other.num_rows() > 0);

        // check the capacity.
        let new_rows = self.rows + other.rows;
        // We need to reallocate memory.
        let cols = self.cols;
        self.reallocate(new_rows, cols);
        // Now create space for other matrix to be fitted in
        self.create_row_space(index, other.num_rows());
        // Finally copy the row data from the other matrix.
        let src_ptr = other.ptr;
        let dst_ptr = self.ptr;
        let src_stride = other.stride();
        let dst_stride = self.stride();
        for i in 0..other.num_rows(){
            let src_offset = other.cell_to_offset(i, 0);
            let dst_offset = self.cell_to_offset(i + index, 0);
            for j in 0..self.cols{
                unsafe {
                    *dst_ptr.offset(dst_offset + (j*dst_stride) as isize) = 
                    *src_ptr.offset(src_offset + (j*src_stride) as isize);
                }
            }
        }
        self
    }



    #[doc = "
    Reallocates the underlying buffer.
    Assumes that requested capacity is greater than zero.

    ## Notes

    A simple reallocate cannot be used. When the 
    number of rows changes, the stride also changes.
    Thus, the matrix elements need to be moved around.
    "] 
    fn reallocate(&mut self, rows : usize, cols : usize){
        let old_capacity = self.rows * self.cols;
        let new_capacity = rows *  cols;
        if old_capacity >= new_capacity{
            // Nothing to do.
            return;
        }
        assert!(new_capacity > 0);
        let new_bytes = new_capacity * mem::size_of::<T>();
        println!("Allocating {} bytes", new_bytes);
        let raw = unsafe {
            allocate(new_bytes, mem::align_of::<T>())
        };
        let dst_ptr = raw as *mut T;
        let src_ptr = self.ptr;
        // Copy data from source to destination.
        let src_stride = self.rows;
        let dst_stride = rows;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let src_offset = (c * src_stride + r) as isize;
                let dst_offset = (c * dst_stride + r) as isize;
                unsafe{
                    *dst_ptr.offset(dst_offset) = *src_ptr.offset(src_offset);
                }
            }

        }
        // Drop older data.
        unsafe {
            let old_bytes = old_capacity * mem::size_of::<T>();
            //println!("Allocating {} bytes", old_bytes);
            deallocate(self.ptr as *mut u8,
                   old_bytes,
                   mem::align_of::<T>());
        }
        // Keep new data
        self.ptr = dst_ptr;
        self.rows = rows;
        self.cols = cols;
    }

    //// Moves column data around and creates space for new columns
    fn create_column_space(&mut self, start: usize, count :usize){
        // The end must not be beyond capacity
        let new_cols = self.cols;
        let old_cols = new_cols - count;
        if start >= new_cols {
            // Nothing to move.
            return;
        }
        let capacity = self.capacity() as isize;
        // count columns starting from start column need to be
        // shifted by count.
        let ptr = self.ptr;
        // Number of columns to shift
        let cols_to_shift =  old_cols - (start + count - 1);
        //println!("start: {:?} count: {:?}, cols to shift {:?}", start, count, cols_to_shift );
        let mut cur_col = old_cols;
        for _ in 0..cols_to_shift{
            cur_col -= 1;
            let dst_col = cur_col + count;
            //println!("src_col: {:?} dst_col: {:?}", cur_col, dst_col);
            let src_offset = self.cell_to_offset(0, cur_col);
            let dst_offset = self.cell_to_offset(0, dst_col);
            debug_assert!(src_offset < capacity);
            debug_assert!(dst_offset < capacity);
            for i in 0..self.rows{
                let ii = i as isize;
                // Some validations
                debug_assert!(src_offset + ii < capacity);
                debug_assert!(dst_offset + ii < capacity);
                unsafe {
                    *ptr.offset(dst_offset + ii) = *ptr.offset(src_offset + ii);
                }
            }
        }
    }

    //// Moves rows around and creates space for new rows
    fn create_row_space(&mut self, start: usize, count :usize){
        // The end must not be beyond capacity
        let new_rows = self.rows;
        let old_rows = new_rows - count;
        if start >= old_rows {
            // Nothing to move.
            return;
        }
        let capacity = self.capacity() as isize;
        // count rows starting from start row need to be
        // shifted by count.
        let ptr = self.ptr;
        // Number of rows to shift
        let rows_to_shift =  old_rows - (start + count - 1);
        let stride = self.stride();
        let mut cur_row = old_rows;
        for _ in 0..rows_to_shift{
            cur_row -= 1;
            let dst_row = cur_row + count;
            let src_offset = self.cell_to_offset(cur_row, 0);
            let dst_offset = self.cell_to_offset(dst_row, 0);
            debug_assert!(src_offset < capacity);
            debug_assert!(dst_offset < capacity);
            for i in 0..self.cols{
                let ii = (i*stride) as isize;
                // Some validations
                debug_assert!(src_offset + ii < capacity);
                debug_assert!(dst_offset + ii < capacity);
                unsafe {
                    *ptr.offset(dst_offset + ii) = 
                    *ptr.offset(src_offset + ii);
                }
            }
        }
    }

}



/// Implementation of Matrix search operations.
impl<T:MagmaBase+Signed+PartialOrd> Search<T> for Matrix<T> {
}



/// Views of a matrix
impl<T:MagmaBase> Matrix<T> {
    /// Creates a view on the matrix
    pub fn view(&self, start_row : usize, start_col : usize , num_rows: usize, num_cols : usize) -> MatrixView<T> {
        let result : MatrixView<T> = MatrixView::new(self, start_row, start_col, num_rows, num_cols);
        result
    }
}




/// These functions are available only for types which support
/// ordering [at least partial ordering for floating point numbers].
impl<T:CommutativeMonoidAddPartial+PartialOrd> Matrix<T> {


    // Returns the minimum scalar value with location
    pub fn min_scalar(&self) -> (T, usize, usize){
        if self.is_empty(){
            panic!(SRError::EmptyMatrix.to_string());
        }
        let mut v = unsafe {self.get_unchecked(0, 0)};
        let ps = self.ptr;
        // The location
        let mut rr = 0;
        let mut cc = 0;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let src_offset = self.cell_to_offset(r, c);
                let s = unsafe{*ps.offset(src_offset)};
                if s < v { 
                    v = s;
                    rr = r;
                    cc = c;
                }
            }
        }
        (v, rr, cc)
    }

    // Returns the maximum scalar value with location
    pub fn max_scalar(&self) -> (T, usize, usize){
        if self.is_empty(){
            panic!(SRError::EmptyMatrix.to_string());
        }
        let mut v = unsafe {self.get_unchecked(0, 0)};
        // The location
        let mut rr = 0;
        let mut cc = 0;
        let ps = self.ptr;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let src_offset = self.cell_to_offset(r, c);
                let s = unsafe{*ps.offset(src_offset)};
                if s > v { 
                    v = s;
                    rr = r;
                    cc = c;
                }
            }
        }
        (v, rr, cc)
    }
    /// Returns the minimum scalar value
    pub fn min_scalar_value(&self) -> T{
        let (v , _, _) = self.min_scalar();
        v
    }    
    /// Returns the maximum scalar value
    pub fn max_scalar_value(&self) -> T{
        let (v , _, _) = self.max_scalar();
        v
    }    
}

impl<T:MagmaBase+Signed+PartialOrd> Matrix<T> {

    // Returns the absolute minimum scalar value
    pub fn min_abs_scalar(&self) -> (T, usize, usize){
        if self.is_empty(){
            panic!(SRError::EmptyMatrix.to_string());
        }
        let mut v = unsafe {self.get_unchecked(0, 0)}.abs();
        // The location
        let mut rr = 0;
        let mut cc = 0;
        let ps = self.ptr;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let src_offset = self.cell_to_offset(r, c);
                let s = unsafe{*ps.offset(src_offset)}.abs();
                if s < v { 
                    v = s;
                    rr = r;
                    cc = c;
                };
            }
        }
        (v, rr, cc)
    }

    // Returns the maximum scalar value
    pub fn max_abs_scalar(&self) -> (T, usize, usize){
        if self.is_empty(){
            panic!(SRError::EmptyMatrix.to_string());
        }
        let mut v = unsafe {self.get_unchecked(0, 0)}.abs();
        // The location
        let mut rr = 0;
        let mut cc = 0;
        let ps = self.ptr;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let src_offset = self.cell_to_offset(r, c);
                let s = unsafe{*ps.offset(src_offset)}.abs();
                if s > v { 
                    v  = s;
                    rr = r;
                    cc = c;
                }
            }
        }
        (v, rr, cc)
    }    

    /// Returns the absolute minimum scalar value
    pub fn min_abs_scalar_value(&self) -> T{
        let (v , _, _) = self.min_abs_scalar();
        v
    }    
    /// Returns the absolute maximum scalar value
    pub fn max_abs_scalar_value(&self) -> T{
        let (v , _, _) = self.max_abs_scalar();
        v
    }    
}

/// These functions are available only for integer matrices
impl<T:MagmaBase + Signed> Matrix<T> {

    /// Returns if an integer matrix is a logical matrix
    //// i.e. all cells are either 0s or 1s.
    pub fn is_logical(&self) -> bool {
        let z : T = Zero::zero();
        let o : T = One::one();
        for c in 0..self.cols{
            for r in 0..self.rows{
                let offset = self.cell_to_offset(r, c);
                unsafe{ 
                    let v = *self.ptr.offset(offset);
                    if v != z && v != o {
                        return false;
                    }
                }
            }
        }
        true
    }
}


/// These functions are available only for floating point matrices
impl<T:FieldPartial+Float> Matrix<T> {
    /// Returns a matrix showing all the cells which are finite
    pub fn is_finite(&self) -> Matrix<u8>{
        let m : Matrix<u8> = Matrix::ones(self.rows, self.cols);
        for c in 0..self.cols{
            for r in 0..self.rows{
                let offset = self.cell_to_offset(r, c);
                unsafe{ 
                    let v = *self.ptr.offset(offset);
                    *m.ptr.offset(offset) = v.is_finite() as u8;
                }
            }
        }
        m
    }

    /// Returns a matrix showing all the cells which are infinite
    pub fn is_infinite(&self) -> Matrix<u8>{
        let m : Matrix<u8> = Matrix::ones(self.rows, self.cols);
        for c in 0..self.cols{
            for r in 0..self.rows{
                let offset = self.cell_to_offset(r, c);
                unsafe{ 
                    let v = *self.ptr.offset(offset);
                    *m.ptr.offset(offset) = v.is_infinite() as u8;
                }
            }
        }
        m
    }
}



impl<T:MagmaBase> Index<usize> for Matrix<T> {
    type Output = T;
    #[inline]
    fn index<'a>(&'a self, index: usize) -> &'a T {
        // The matrix is column major order
        let (r, c) = self.index_to_cell(index);
        let offset = c * self.stride() + r;
        unsafe {
            &*self.ptr.offset(offset as isize)
        }
    }
}



impl<T:MagmaBase> Matrix<T>{
    /// This function is for internal use only.
    #[inline]
    fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
        unsafe {
            mem::transmute(Slice {
                data: self.as_mut_ptr() as *const T,
                len: self.capacity(),
            })
        }
    }
}



/// Implementation of Clone interface
impl <T:MagmaBase> Clone for Matrix<T> {

    /// Creates a clone of the matrix
    fn clone(&self )-> Matrix<T> {
        let m : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = m.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pb.offset(i) = *pa.offset(i);
            }
        }
        m
    }
}

impl <T:MagmaBase> fmt::Debug for Matrix<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // We need to find out the number of characters needed
        // to show each value.
        // maximum value
        let mut strings : Vec<String> = Vec::with_capacity(self.num_cells());
        let mut n : usize = 0;
        let ptr = self.ptr;
        for r in 0..self.rows{
            for c in 0..self.cols{
                let offset = self.cell_to_offset(r, c);
                let v = unsafe {*ptr.offset(offset)};
                let s = format!("{:?}", v);
                let slen = s.len();
                strings.push(s);
                if slen > n {
                    n = slen;
                }
            }
        }
        //println!("{}, {}, {}", v, s, n);
        try!(write!(f, "["));
        // Here we print row by row
        for r in 0..self.rows {
           try!(write!(f, "\n  "));
            for c in 0..self.cols{
                let offset =  r *self.cols + c;
                let ref s = strings[offset];
                let extra = n + 2 - s.len();
                for _ in 0..extra{
                    try!(write!(f, " "));
                }
                try!(write!(f, "{}", s));
            }
        }
        try!(write!(f, "\n]"));
        Ok(())
    }
}

impl <T:MagmaBase> fmt::Display for Matrix<T> {
    /// Display and Debug versions are same
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}


/// Matrix addition support
impl<'a, 'b, T:CommutativeMonoidAddPartial> ops::Add<&'b Matrix<T>> for &'a Matrix<T> {
    type Output = Matrix<T>;
    fn add(self, rhs: &'b Matrix<T>) -> Matrix<T> {
        // Validate dimensions are same.
        if self.size() != rhs.size(){
            panic!(SRError::DimensionsMismatch.to_string());
        }
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = rhs.ptr;
        let pc = result.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pc.offset(i) = *pa.offset(i) + *pb.offset(i);
            }
        }
        result
    }
}


/// Matrix subtraction support
impl<'a, 'b, T:QuasiGroupAddPartial> ops::Sub<&'b Matrix<T>> for &'a Matrix<T>{
    type Output = Matrix<T>;
    fn sub(self, rhs: &'b Matrix<T>) -> Matrix<T> {
        // Validate dimensions are same.
        if self.size() != rhs.size(){
            panic!(SRError::DimensionsMismatch.to_string());
        }
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = rhs.ptr;
        let pc = result.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pc.offset(i) = *pa.offset(i) - *pb.offset(i);
            }
        }
        result
    }
}




/// Matrix equality check support
impl<T:MagmaBase> cmp::PartialEq for Matrix<T>{
    fn eq(&self, other: &Matrix<T>) -> bool {
        let pa = self.ptr as *const  T;
        let pb = other.ptr as *const  T;
        for c in 0..self.cols{
            for r in 0..self.rows{
                let offset_a = self.cell_to_offset(r, c);
                let offset_b = other.cell_to_offset(r, c);
                let va = unsafe{*pa.offset(offset_a)};
                let vb = unsafe{*pb.offset(offset_b)};
                if va != vb {
                    return false;
                }
            }
        }
        true
    }
}

// Element wise operations.
impl<T:CommutativeMonoidAddPartial> Matrix<T> {
    /// Adds matrices element by element
    pub fn add_elt(&self, rhs: &Matrix<T>) -> Matrix<T> {
        // Validate dimensions are same.
        if self.size() != rhs.size(){
            panic!(SRError::DimensionsMismatch.to_string());
        }
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = rhs.ptr;
        let pc = result.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pc.offset(i) = *pa.offset(i) + *pb.offset(i);
            }
        }
        result
    }
}

impl<T:CommutativeMonoidAddPartial+ops::Sub<Output=T>> Matrix<T> {
    /// Subtracts matrices element by element
    pub fn sub_elt(&self, rhs: &Matrix<T>) -> Matrix<T> {
        // Validate dimensions are same.
        if self.size() != rhs.size(){
            panic!(SRError::DimensionsMismatch.to_string());
        }
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = rhs.ptr;
        let pc = result.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pc.offset(i) = *pa.offset(i) - *pb.offset(i);
            }
        }
        result
    }
}
impl<T:CommutativeMonoidMulPartial> Matrix<T> {
    /// Multiplies matrices element by element
    pub fn mul_elt(&self, rhs: &Matrix<T>) -> Matrix<T> {
        // Validate dimensions are same.
        if self.size() != rhs.size(){
            panic!(SRError::DimensionsMismatch.to_string());
        }
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = rhs.ptr;
        let pc = result.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pc.offset(i) = *pa.offset(i) * *pb.offset(i);
            }
        }
        result
    }

    /// Computs power of matrix elements
    pub fn pow_elt(&self, n : usize) -> Matrix<T> {
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pc = result.ptr;
        let cap = self.capacity();
        unsafe{
            for i_ in 0..cap{
                let i = i_ as isize;
                let v = *pa.offset(i);
                let mut result : T = One::one();
                for _ in 1..n{
                    result = result * v; 
                }
                *pc.offset(i) = result;
            }
        }
        result
    }
}

impl<T:CommutativeMonoidMulPartial+ops::Div<Output=T>> Matrix<T> {
    /// Divides matrices element by element
    pub fn div_elt(&self, rhs: &Matrix<T>) -> Matrix<T> {
        // Validate dimensions are same.
        if self.size() != rhs.size(){
            panic!(SRError::DimensionsMismatch.to_string());
        }
        let result : Matrix<T> = Matrix::new(self.rows, self.cols);
        let pa = self.ptr;
        let pb = rhs.ptr;
        let pc = result.ptr;
        let n = self.capacity();
        unsafe{
            for i_ in 0..n{
                let i = i_ as isize;
                *pc.offset(i) = *pa.offset(i) / *pb.offset(i);
            }
        }
        result
    }

}

impl<T:MagmaBase> Drop for Matrix<T> {
    fn drop(&mut self) {
        if self.num_cells() != 0 {
            unsafe {
                util::memory::dealloc(self.ptr, self.capacity())
            }
        }
    }
}

/******************************************************
 *
 *   Utility functions for debugging of Matrix
 *
 *******************************************************/

impl<T:MagmaBase> Matrix<T> {
    pub fn print_state(&self){
        let capacity = self.capacity();
        let bytes = capacity * mem::size_of::<T>();
        println!("Rows: {}, Cols: {}, Capacity: {}, Bytes; {}, Buffer: {:p}, End : {:p}", 
            self.rows, self.cols,
            capacity, bytes, self.ptr, unsafe {
                self.ptr.offset(capacity as isize)
            });
    }
}


/******************************************************
 *
 *   Private implementation of Matrix
 *
 *******************************************************/

impl<T:MagmaBase> Matrix<T> {
    /// Returns a slice into `self`.
    //#[inline]
    pub fn as_slice_<'a>(&'a self) -> &'a [T] {
        unsafe { mem::transmute(Slice { data: self.as_ptr(), len: self.capacity() }) }
    }

}



/******************************************************
 *
 *   Unit tests follow.
 *
 *******************************************************/


#[cfg(test)]
mod test {

    use  super::{Matrix, MatrixI64, MatrixF64};
    use matrix::constructors::*;
    use matrix::traits::*;
    use num::Float;

    #[test]
    fn  test_create_mat0(){
        let m : MatrixI64 = Matrix::new(3, 4);
        assert_eq!(m.num_cells(), 12);
        assert_eq!(m.size(), (3, 4));
        assert_eq!(m.smaller_dim(), 3);
        assert_eq!(m.larger_dim(), 4);
        // NOTE: we cannot use the contents of the
        // matrix as they are uninitialized.
        let m : MatrixI64 = Matrix::zeros(3, 4);
        let v : i64 = m.get(0, 0).unwrap();
        assert_eq!(v, 0i64);
    }

    #[test]
    fn test_from_slice_rw0(){
        let  m : MatrixI64 = Matrix::from_slice_rw(3, 3, &[
            1, 2, 3, 
            4, 5, 6,
            7, 8, 9
            ]);
        assert_eq!(m.get(0, 0).unwrap(), 1);
        assert_eq!(m.get(0, 1).unwrap(), 2);
        assert_eq!(m.get(0, 2).unwrap(), 3);
        assert_eq!(m.get(1, 0).unwrap(), 4);
        assert_eq!(m.get(1, 1).unwrap(), 5);
        assert_eq!(m.get(1, 2).unwrap(), 6);
        assert_eq!(m.get(2, 0).unwrap(), 7);
        assert_eq!(m.get(2, 1).unwrap(), 8);
    }


    #[test]
    fn test_from_iter_cw0(){
        for _ in 0..100{
            let m : MatrixI64 = Matrix::from_iter_cw(4, 4, 1..20);
            let b: Vec<i64> = (1..17).collect();
            assert!(m.as_slice_() == b.as_slice());
            let m : MatrixI64 = Matrix::from_iter_cw(4, 8, 1..16);
            assert_eq!(m.get(0, 0).unwrap(), 1);
            assert_eq!(m.get(2, 2).unwrap(), 11);
            let mut b: Vec<i64> = (1..16).collect();
            for _ in 0..17{
                b.push(0);
            }
            assert_eq!(m.as_slice_(), b.as_slice());
        }
    }

    #[test]
    fn test_index0(){
        let m : MatrixI64 = Matrix::from_iter_cw(4, 4, (1..20));
        let x = m[4];
        assert_eq!(x, 5);
    }

    #[test]
    fn test_cell_index_mapping(){
        let rows = 20;
        let cols = 10;
        let m : MatrixI64 = Matrix::new(rows, cols);
        assert_eq!(m.index_to_cell(3 + 2*rows), (3, 2));
        assert_eq!(m.cell_to_index(3, 2), 3 + 2*rows);
        assert_eq!(m.cell_to_index(5, 7), 145);
        assert_eq!(m.index_to_cell(145), (5, 7));
    }

    #[test]
    fn test_to_std_vec(){
        let m : MatrixI64 = Matrix::from_iter_cw(4, 3, 0..12);
        let v1 = m.to_std_vec();
        let v2 : Vec<i64> = (0..12).collect();
        assert_eq!(v1, v2);
    }

    #[test]
    fn test_ones(){
        let m : MatrixI64 = Matrix::ones(4, 2);
        let v = vec![1i64, 1, 1, 1, 1, 1, 1, 1];
        assert_eq!(m.to_std_vec(), v);
    }

    #[test]
    fn test_sum(){
        let m : MatrixI64 = Matrix::ones(4, 2);
        let m2 = &m  + &m;
        let v = vec![2i64, 2, 2, 2, 2, 2, 2, 2];
        assert_eq!(m2.to_std_vec(), v);
    }

    #[test]
    #[should_panic]
    fn test_sum_fail(){
        let m1 : MatrixI64 = Matrix::ones(4, 2);
        let m2 : MatrixI64 = Matrix::ones(3, 2);
        &m1 + &m2;
    }

    #[test]
    fn test_sub(){
        let m : MatrixI64 = Matrix::ones(4, 2);
        let m3 = &(&m  + &m) + &m;
        let m2 = &m3 - &m;  
        let v = vec![2i64, 2, 2, 2, 2, 2, 2, 2];
        assert_eq!(m2.to_std_vec(), v);
    }

    #[test]
    fn test_sub_float(){
        let m : MatrixF64 = Matrix::ones(4, 2);
        let m3 = &(&m  + &m) + &m;
        let m2 = &m3 - &m;  
        let v = vec![2f64, 2., 2., 2., 2., 2., 2., 2.];
        assert_eq!(m2.to_std_vec(), v);
    }
    #[test]
    #[should_panic]
    fn test_sub_fail(){
        let m1 : MatrixI64 = Matrix::ones(4, 2);
        let m2 : MatrixI64 = Matrix::ones(3, 2);
        &m1 - &m2;
    }


    #[test]
    fn test_eq(){
        let m1 : MatrixI64 = Matrix::from_iter_cw(2, 2, 0..4);
        let m2 : MatrixI64 = Matrix::from_iter_cw(2, 2, 0..4);
        assert_eq!(m1, m2);
        let v = vec![1.0f64, 2., 3., 4.];
        let m1 : MatrixF64 = Matrix::from_slice_cw(2, 2, v.as_slice());
        let m2 : MatrixF64 = Matrix::from_slice_cw(2, 2, v.as_slice());
        assert_eq!(m1, m2);
    }

    #[test]
    fn test_from_scalar(){
        let  m : MatrixI64  = Matrix::from_scalar(2);
        assert!(m.is_scalar());
        assert_eq!(m.to_std_vec(), vec![2]);
        assert_eq!(m.to_scalar(), 2);
    }
    #[test]
    fn test_rep_mat(){
        let m  : MatrixI64 = Matrix::from_iter_cw(2, 2,  0..4);
        let m2 = m.repeat_matrix(2, 2);
        assert_eq!(m2.num_cells(), 16);
        assert_eq!(m2.num_rows(), 4);
        assert_eq!(m2.num_cols(), 4);
        assert_eq!(m2.to_std_vec(), vec![0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3]);
    }

    #[test]
    fn test_is_vector(){
        let m : MatrixI64 = Matrix::new(3,1);
        assert!(m.is_vector());
        let m : MatrixI64 = Matrix::new(1,4);
        assert!(m.is_vector());
        let m : MatrixI64 = Matrix::new(1,1);
        assert!(!m.is_vector());
        let m : MatrixI64 = Matrix::new(3,3);
        assert!(!m.is_vector());
    }


    #[test]
    fn test_is_empty(){
        let m : MatrixI64 = Matrix::new(3,1);
        assert!(!m.is_empty());
        let m : MatrixI64 = Matrix::new(4, 0);
        assert!(m.is_empty());
        let m : MatrixI64 = Matrix::new(0, 4);
        assert!(m.is_empty());
        let m : MatrixI64 = Matrix::new(0, 0);
        assert!(m.is_empty());
    }

    #[test]
    fn test_is_finite(){
        let v = vec![0f64, Float::nan(), Float::nan(), 
        Float::infinity(), Float::neg_infinity(), 2., 3., 4.];
        let m : MatrixF64 = Matrix::from_slice_cw(2, 4, v.as_slice());
        let f = m.is_finite();
        assert_eq!(f.to_std_vec(), vec![1, 0, 0, 0, 0, 
            1, 1, 1]);
        let f = m.is_infinite();
        assert_eq!(f.to_std_vec(), vec![0, 0, 0, 1, 1, 
            0, 0, 0]);
    }


    #[test]
    fn test_is_logical(){
        let m : MatrixI64 = Matrix::from_iter_cw(4, 4, (0..16).map(|x| x % 2));
        assert!(m.is_logical());
        let m = &m + &m;
        assert!(!m.is_logical());
    }

    #[test]
    fn test_reshape(){
        let v = vec![1, 2, 3, 4, 
        5, 6, 7, 8,
        9, 10, 11, 12];
        let mut m1 : MatrixI64 = Matrix::from_slice_cw(8, 1, v.as_slice());
        m1.reshape(2, 4);
        let m2 : MatrixI64 = Matrix::from_slice_cw(2, 4, v.as_slice());
        assert_eq!(m1, m2);
    }

    #[test]
    fn test_max(){
        // Note the first 4 entries in v form the first column
        // in the matrix.
        let v = vec![4, 5, 11, 12, 
        0, 1, 2, 3, 
        19, 17, 3, 1, 
        7, 8, 5, 6];
        let m : MatrixI64 = Matrix::from_slice_cw(4, 4, v.as_slice());
        let m2 = m.max_row_wise();
        assert!(m2.is_vector());
        assert!(m2.is_col());
        assert_eq!(m2.to_std_vec(), vec![19, 17, 11, 12]);

        let m2 = m.min_row_wise();
        assert!(m2.is_vector());
        assert!(m2.is_col());
        assert_eq!(m2.to_std_vec(), vec![0, 1, 2, 1]);

        let m2 = m.max_col_wise();
        assert!(m2.is_vector());
        assert!(m2.is_row());
        assert_eq!(m2.to_std_vec(), vec![12, 3, 19, 8]);
        


        let m2 = m.min_col_wise();
        assert!(m2.is_vector());
        assert!(m2.is_row());
        assert_eq!(m2.to_std_vec(), vec![4, 0, 1, 5]);

        assert_eq!(m.min_scalar_value(), 0);
        assert_eq!(m.max_scalar_value(), 19);
    }

    #[test]
    fn test_mul_elt(){
        let m  : MatrixI64 = Matrix::from_iter_cw(2, 2,  0..4);
        let m2 = m.mul_elt(&m);
        let m3  : MatrixI64 = Matrix::from_iter_cw(2, 2,  (0..4).map(|x| x*x));
        assert_eq!(m2, m3);
    }


    #[test]
    fn test_div_elt(){
        let m  : MatrixI64 = Matrix::from_iter_cw(2, 2,  (1..20));
        let m2 = &m + &m;
        let m3 = m2.div_elt(&m);
        assert_eq!(m3.to_std_vec(), vec![2,2,2,2]);
    }


    #[test]
    fn test_identity(){
        let m : MatrixI64 = Matrix::identity(3, 2);
        assert_eq!(m.to_std_vec(), vec![1, 0, 0, 0, 1, 0]);
        assert!(m.is_identity());
        let m : MatrixI64 = Matrix::identity(2, 2);
        assert_eq!(m.to_std_vec(), vec![1, 0, 0, 1]);
        assert!(m.is_identity());
        let m : MatrixI64 = Matrix::identity(2, 3);
        assert_eq!(m.to_std_vec(), vec![1, 0, 0, 1, 0, 0]);
        assert!(m.is_identity());
        let m  : MatrixI64 = Matrix::from_iter_cw(2, 2,  0..4);
        assert!(!m.is_identity());
    }

    #[test]
    fn test_is_square(){
        let m : MatrixI64 = Matrix::new(3,4);
        assert!(!m.is_square());
        let m : MatrixI64 = Matrix::new(100,100);
        assert!(m.is_square());
    }

    #[test]
    fn test_pow(){
        let m : MatrixI64  = Matrix::identity(4, 4);
        let m2 = m.copy_mul_scalar(2);
        assert!(m.is_square());
        let m4 = m2.pow(4);
        let m16 = m.copy_mul_scalar(16);
        assert_eq!(m4, m16); 
        let m  : MatrixI64 = Matrix::from_iter_cw(2, 2,  0..4);
        assert!(m.is_square());
        let m3 = m.pow(3);
        assert!(m3.is_square());
        assert_eq!(m3.to_std_vec(), vec![6, 11, 22, 39]);
        assert_eq!(m.pow(1).to_std_vec(), vec![0, 1, 2, 3]);
        assert_eq!(m.pow(2), &m * &m);
        // This is UGLY. I wish I could fix it.
        let x = &(&(&(&(&(&(&(&(&m * &m) * &m) * &m) * &m) * &m) * &m) * &m) * &m) * &m;
        assert_eq!(m.pow(10), x);
    }

    #[test]
    fn test_unary_minus(){
        let m  : MatrixI64 = Matrix::from_iter_cw(2, 2,  0..4);
        let z : MatrixI64 = Matrix::zeros(2,2);
        let m2 = m.unary_minus();
        let m3 = &z - &m;
        assert_eq!(m2, m3);
    }


    #[test]
    fn test_diag_from_vector(){
        // repeat the same test a hundred times
        for _ in 0..100{
            let v  : MatrixI64 = Matrix::from_iter_cw(4, 1, (20..30));
            assert!(v.is_vector());
            let m = Matrix::diag_from_vec(&v);
            assert!(!m.is_empty());
            assert!(!m.is_vector());
            println!("{:?}", m);
            assert!(m.is_diagonal());
            assert_eq!(m.num_cells(), 16);
            let mut m2 : MatrixI64 = Matrix::zeros(4, 4);
            m2.set(0, 0, 20);
            m2.set(1, 1, 21);
            m2.set(2, 2, 22);
            m2.set(3, 3, 23);
            assert_eq!(m, m2);
        }
    }

    #[test]
    fn test_diagonal(){
        let m  : MatrixI64 = Matrix::from_iter_cw(4, 5, (10..30));
        let v = m.diagonal_vector();
        println!("m: {} v: {}", m, v);
        assert!(v.is_vector());
        assert_eq!(v.num_cells(), 4);
        let v2 : MatrixI64 = Matrix::from_slice_cw(4, 1, vec![10, 15, 20, 25].as_slice());
        assert_eq!(v, v2);
    }


    #[test]
    fn test_triangular(){
        let m = matrix_cw_f64(3, 3, &[1., 0., 0., 
            4., 5., 0.,
            6., 2., 3.]);
        println!("m: {:?}", m);
        assert!(m.is_ut());
        assert!(!m.is_lt());
        assert!(m.is_triangular());
        let m  = m.transpose();
        assert!(!m.is_ut());
        assert!(m.is_lt());
        assert!(m.is_triangular());
    }

    #[test]
    fn test_trace(){
        let m = matrix_cw_f64(3, 3, &[1., 0., 0., 
            4., 5., 0.,
            6., 2., 3.]);
        println!("{}", m.trace());
        assert_eq!(m.trace(), 9.);
    }

    #[test]
    fn test_extract_triangular(){
        let m = matrix_rw_i64(3,3,&[
            1, 2, 3,
            4, 5, 6,
            7, 8, 9
            ]);
        let mu = matrix_rw_i64(3,3,&[
            1, 2, 3,
            0, 5, 6,
            0, 0, 9
            ]);
        let ml = matrix_rw_i64(3,3,&[
            1, 0, 0,
            4, 5, 0,
            7, 8, 9
            ]);
        assert_eq!(m.ut(), mu);
        assert_eq!(m.lt(), ml);
    }

    #[test]
    fn test_extract_diagonal_matrix(){
        let m = matrix_rw_i64(3,3,&[
            1, 2, 3,
            4, 5, 6,
            7, 8, 9
            ]);
        let md = matrix_rw_i64(3,3,&[
            1, 0, 0,
            0, 5, 0,
            0, 0, 9
            ]);
        assert_eq!(m.diagonal_matrix(), md);
        assert_eq!(m.diagonal_vector(), vector_i64(&[1, 5, 9]));
        // More columns than rows
        let m = matrix_rw_i64(3,4,&[
            1, 2, 3, 11,
            4, 5, 6, 12,
            7, 8, 9, 19
            ]);
        let md = matrix_rw_i64(3,4,&[
            1, 0, 0, 0,
            0, 5, 0, 0,
            0, 0, 9, 0
            ]);
        assert_eq!(m.diagonal_matrix(), md);
        assert_eq!(m.diagonal_vector(), vector_i64(&[1, 5, 9]));
        // More rows than columns
        let m = matrix_rw_i64(4,3,&[
            1, 2, 3,
            4, 5, 6,
            7, 8, 9,
            10, 11, 12
            ]);
        let md = matrix_rw_i64(4,3,&[
            1, 0, 0,
            0, 5, 0,
            0, 0, 9,
            0, 0, 0
            ]);
        assert_eq!(m.diagonal_matrix(), md);
        assert_eq!(m.diagonal_vector(), vector_i64(&[1, 5, 9]));
    }

    #[test]
    fn test_unit_vector(){
        let v : MatrixI64 = Matrix::unit_vector(10, 3);
        let mut m : MatrixI64 = Matrix::zeros(10, 1);
        m.set(3, 0, 1);
        assert_eq!(v, m);
    }

    #[test]
    fn test_row_col_iter(){
        let m  : MatrixI64 = Matrix::from_iter_cw(4, 5, (10..30));
        let r = m.row_iter(0);
        let v : Vec<i64> = r.collect();
        assert_eq!(v, vec![10, 14, 18, 22, 26]);
        let r = m.col_iter(2);
        let v : Vec<i64> = r.collect();
        assert_eq!(v, vec![18, 19, 20, 21]);
        let m  : MatrixI64 = Matrix::from_iter_cw(3, 2, (10..30));
        let r = m.cell_iter();
        let v : Vec<i64> = r.collect();
        assert_eq!(v, vec![10, 11, 12, 13, 14, 15]);
    }

    #[test]
    fn test_add_columns(){
        let mut m1 :  MatrixI64 = Matrix::from_iter_cw(2, 3, (11..100));
        let m2 :  MatrixI64 = Matrix::from_iter_cw(2, 4, (11..100));
        let m3 : MatrixI64  = Matrix::from_iter_cw(2, 1, (17..100));
        let m4 :  MatrixI64 = Matrix::from_iter_cw(2, 5, (9..100));
        let m5 : MatrixI64  = Matrix::from_iter_cw(2, 1, (9..100));
        // matrix size 2x3.
        println!("{}", m1);
        // adding 2x1 to get 2x4.
        m1.append_columns(&m3);
        println!("{}", m1);
        assert_eq!(m1, m2);
        // adding 2x1 to get 2x5.
        m1.prepend_columns(&m5);
        println!("{}", m1);
        assert_eq!(m1, m4);
        let m6 : MatrixI64  = Matrix::from_iter_cw(2, 1, (5..100));
        m1.prepend_columns(&m6);
        println!("{}", m1);
        let m7 : MatrixI64  = Matrix::from_iter_cw(2, 1, (7..100));
        m1.insert_columns(1, &m7);
        println!("{}", m1);
    }


    #[test]
    fn test_add_rows(){
        let mut m1 :  MatrixI64 = Matrix::from_iter_cw(2, 3, (11..100)).transpose();
        let m2 :  MatrixI64 = Matrix::from_iter_cw(2, 4, (11..100)).transpose();
        let m3 : MatrixI64  = Matrix::from_iter_cw(2, 1, (17..100)).transpose();
        let m4 :  MatrixI64 = Matrix::from_iter_cw(2, 5, (9..100)).transpose();
        let m5 : MatrixI64  = Matrix::from_iter_cw(2, 1, (9..100)).transpose();
        println!("m1: {}", m1);
        m1.print_state();
        println!("m2: {}", m2);
        println!("m3: {}", m3);
        println!("m4: {}", m4);
        m4.print_state();
        m1.append_rows(&m3);
        println!("m1 = [m1 ; m3] {}", m1);
        m1.print_state();
        println!("m4: {}", m4);
        m4.print_state();
        //assert_eq!(m1, m2);
        println!("\nm4 {}", m4);
        m4.print_state();
        println!("m5 {}", m5);
        m1.prepend_rows(&m5);
        println!("m1 = [m5 ; m1] {}", m1);
        m1.print_state();
        println!("\nm4 {}", m4);
        m4.print_state();
        assert_eq!(m1, m4);
        let m6 : MatrixI64  = Matrix::from_iter_cw(2, 1, (5..100)).transpose();
        m1.prepend_rows(&m6);
        println!("{}", m1);
        let m7 : MatrixI64  = Matrix::from_iter_cw(2, 1, (7..100)).transpose();
        m1.insert_rows(1, &m7);
        println!("{}", m1);
    }

    #[test]
    fn test_inner_product(){
        let m1 : MatrixI64 = Matrix::from_slice_cw(3, 1, vec![2, 1, 1].as_slice());
        let m2 : MatrixI64 = Matrix::from_slice_cw(3, 1, vec![1, 1, 2].as_slice());
        let result = m1.inner_prod(&m2);
        assert_eq!(result, 5);
    }


    #[test]
    fn test_outer_product(){
        let m1 : MatrixI64 = Matrix::from_slice_cw(3, 1, vec![2, 1, 1].as_slice());
        let m2 : MatrixI64 = Matrix::from_slice_cw(3, 1, vec![1, 1, 2].as_slice());
        let result = m1.outer_prod(&m2);
        let m3 : MatrixI64 = Matrix::from_slice_cw(3, 3, vec![2, 1, 1, 2, 1, 1, 4, 2, 2].as_slice());
        assert_eq!(result, m3);
    }

    #[test]
    fn test_max_abs_scalar_in_row(){
        let m = matrix_rw_i64(3, 3, &[
            2, 93, 9, 
            2, 71, -79, 
            -83, 62, 6]);
        assert_eq!(m.max_abs_scalar_in_row(0, 0, 3), (93, 1));
        assert_eq!(m.max_abs_scalar_in_row(1, 0, 3), (79, 2));
        assert_eq!(m.max_abs_scalar_in_row(2, 0, 3), (83, 0));
        assert_eq!(m.max_abs_scalar_in_row(1, 0, 2), (71, 1));
        assert_eq!(m.max_abs_scalar_in_row(2, 1, 2), (62, 1));
    }

    #[test]
    fn test_max_abs_scalar_in_col(){
        let m = matrix_cw_i64(3, 3, &[
            2, 93, 9, 
            2, 71, -79, 
            -83, 62, 6]);
        assert_eq!(m.max_abs_scalar_in_col(0, 0, 3), (93, 1));
        assert_eq!(m.max_abs_scalar_in_col(1, 0, 3), (79, 2));
        assert_eq!(m.max_abs_scalar_in_col(2, 0, 3), (83, 0));
        assert_eq!(m.max_abs_scalar_in_col(1, 0, 2), (71, 1));
        assert_eq!(m.max_abs_scalar_in_col(2, 1, 2), (62, 1));
    }

    #[test]
    fn test_permute_rows(){
        let m = matrix_rw_i64(4, 3, &[
            1, 2, 3, 
            4, 5, 6,
            7, 8, 9,
            10, 11, 12
            ]);
        let permutation = vector_u16(&[0, 3, 1, 2]);
        let m = m.permuted_rows(&permutation);
        let m2 = matrix_rw_i64(4, 3, &[
            1, 2, 3, 
            10, 11, 12,
            4, 5, 6,
            7, 8, 9,
            ]);
        assert_eq!(m, m2);
    }

    #[test]
    fn test_permute_cols(){
        let m = matrix_rw_i64(4, 3, &[
            1, 2, 3, 
            4, 5, 6,
            7, 8, 9,
            10, 11, 12
            ]);
        let permutation = vector_u16(&[2, 0, 1]);
        let m = m.permuted_cols(&permutation);
        let m2 = matrix_rw_i64(4, 3, &[
            3, 1, 2,
            6, 4, 5,
            9, 7, 8,
            12, 10, 11,
            ]);
        assert_eq!(m, m2);
    }
}

/******************************************************
 *
 *   Bench marks follow.
 *
 *******************************************************/


#[cfg(test)]
mod bench {
    //extern crate test;
    //use self::test::Bencher;

}