Example #1
0
        public static CompressedColumnStorage <T> Get <T>(string resource)
            where T : struct, IEquatable <T>, IFormattable
        {
            try
            {
                string type = (typeof(T) == typeof(double)) ? "Double" : "Complex";

                string path = NS.Replace("{Type}", type) + "." + resource;

                object obj;

                if (cache.TryGetValue(path, out obj))
                {
                    return((CompressedColumnStorage <T>)obj);
                }

                var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path);

                var matrix = MatrixMarketReader.ReadMatrix <T>(stream);

                cache.Add(path, matrix);

                return(matrix);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #2
0
        public void CanReadSparseHermitianComplexMatrix()
        {
            var sb = new StringBuilder();

            sb.AppendLine("%%MatrixMarket matrix coordinate complex hermitian");
            sb.AppendLine("5 5 7");
            sb.AppendLine("1 1  1.0 0");
            sb.AppendLine("2 2  10.5 0");
            sb.AppendLine("4 2  250.5 22.22");
            sb.AppendLine("3 3  1.5e-2 0");
            sb.AppendLine("4 4  -2.8e2 0.0");
            sb.AppendLine("5 5  12. 0.");
            sb.AppendLine("5 4  0 33.32");

            var m = MatrixMarketReader.ReadMatrix <Complex>(new StringReader(sb.ToString()));

            Assert.IsInstanceOf <LinearAlgebra.Complex.SparseMatrix>(m);
            Assert.AreEqual(5, m.RowCount);
            Assert.AreEqual(5, m.ColumnCount);
            Assert.AreEqual(9, ((LinearAlgebra.Complex.SparseMatrix)m).NonZerosCount);
            Assert.AreEqual(1.0d, m[0, 0].Real);
            Assert.AreEqual(10.5d, m[1, 1].Real);
            Assert.AreEqual(250.5d, m[3, 1].Real);
            Assert.AreEqual(22.22d, m[3, 1].Imaginary);
            Assert.AreEqual(-22.22d, m[1, 3].Imaginary);
            Assert.AreEqual(-280d, m[3, 3].Real);
            Assert.AreEqual(0d, m[4, 3].Real);
            Assert.AreEqual(33.32d, m[4, 3].Imaginary);
            Assert.AreEqual(-33.32d, m[3, 4].Imaginary);
        }
Example #3
0
        public void CanReadDenseSkewSymmetricMatrix()
        {
            /*  0  1  2  3
            *   1  0  6  7
            *   2  6  0 11
            *   3  7 11  0  */

            var sb = new StringBuilder();

            sb.AppendLine("%%MatrixMarket matrix array integer skew-symmetric");
            sb.AppendLine("4 4");
            sb.Append("1\n2\n3\n6\n7\n11");

            var m = MatrixMarketReader.ReadMatrix <double>(new StringReader(sb.ToString()));

            Assert.IsInstanceOf <LinearAlgebra.Double.DenseMatrix>(m);
            Assert.AreEqual(4, m.RowCount);
            Assert.AreEqual(4, m.ColumnCount);
            Assert.AreEqual(0.0, m.Diagonal().InfinityNorm());
            Assert.AreEqual(0d, m[0, 0]);
            Assert.AreEqual(1d, m[1, 0]);
            Assert.AreEqual(1d, m[0, 1]);
            Assert.AreEqual(7d, m[3, 1]);
            Assert.AreEqual(7d, m[1, 3]);
        }
        public static void Main()
        {
            //create the MatrixMarketReader
            SingleMatrixReader reader = new MatrixMarketReader();

            //create a matrix from a Matrix Market text file by passing the
            //reader the name/path of the file
            Matrix matrix = reader.ReadMatrix("somefile.mtx", StorageType.Dense);

            //create a matrix from a Matrix Market text file by passing the
            //reader the file stream.  the stream could have been any type
            //of stream that contains the matrix data.
            using (Stream stream = File.Open("somefile.mtx", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                matrix = reader.ReadMatrix(stream, StorageType.Dense);
            }
        }
Example #5
0
        public void CanReadFudao007AsSingle()
        {
            var m = MatrixMarketReader.ReadMatrix <float>("./data/MatrixMarket/fidap007.mtx");

            Assert.IsInstanceOf <LinearAlgebra.Single.SparseMatrix>(m);
            Assert.AreEqual(1633, m.RowCount);
            Assert.AreEqual(1633, m.ColumnCount);
            Assert.GreaterOrEqual(54487, ((LinearAlgebra.Single.SparseMatrix)m).NonZerosCount);
            Assert.Less(46000, ((LinearAlgebra.Single.SparseMatrix)m).NonZerosCount);
            Assert.AreEqual(-6.8596032449032e+06f, m[1604, 1631]);
            Assert.AreEqual(-9.1914585107976e+06f, m[1616, 1628]);
            Assert.AreEqual(7.9403870156486e+07f, m[905, 726]);
        }
Example #6
0
        public void Should_solve_tridiagonal_matrix_system()
        {
            var a = MatrixMarketReader.ReadMatrix <double>("matrix1.mtx");
            var b = MatrixMarketReader.ReadVector <double>("vector1.mtx");

            var result = GmresSolver.Solve(a, b, 15, 1);

            result.IsConverged.Should().BeTrue();
            result.OuterIterations.Should().Be(0);
            result.InnerIterations.Should().Be(11);
            foreach (var xValue in result.X)
            {
                xValue.Should().BeApproximately(1.0, GmresSolver.DefaultEpsilon);
            }
        }
Example #7
0
 public void CanReadFudao007AsDouble()
 {
     using (Stream stream = TestData.Data.ReadStream("MatrixMarket.fidap007.mtx"))
     {
         var m = MatrixMarketReader.ReadMatrix <double>(stream);
         Assert.IsInstanceOf <LinearAlgebra.Double.SparseMatrix>(m);
         Assert.AreEqual(1633, m.RowCount);
         Assert.AreEqual(1633, m.ColumnCount);
         Assert.GreaterOrEqual(54487, ((LinearAlgebra.Double.SparseMatrix)m).NonZerosCount);
         Assert.Less(46000, ((LinearAlgebra.Double.SparseMatrix)m).NonZerosCount);
         Assert.AreEqual(-6.8596032449032e+06d, m[1604, 1631]);
         Assert.AreEqual(-9.1914585107976e+06d, m[1616, 1628]);
         Assert.AreEqual(7.9403870156486e+07d, m[905, 726]);
     }
 }
Example #8
0
        public int Preload <T>() where T : struct, IEquatable <T>, IFormattable
        {
            int count = 0;

            foreach (var item in generalList)
            {
                item.Matrix = MatrixMarketReader.ReadMatrix <T>(item.Path);
                count++;
            }

            foreach (var item in symmetricList)
            {
                item.Matrix = MatrixMarketReader.ReadMatrix <T>(item.Path);
                count++;
            }

            return(count);
        }
Example #9
0
        public void Should_solve_dense_matrix_system()
        {
            var a = MatrixMarketReader.ReadMatrix <double>("matrix2.mtx");
            var b = MatrixMarketReader.ReadVector <double>("vector2.mtx");

            var result = GmresSolver.Solve(a, b);

            result.IsConverged.Should().BeTrue();
            result.OuterIterations.Should().Be(0);
            result.InnerIterations.Should().Be(6);

            var expectedX = new[] { -4.0306249, 3.3608880, 3.8133424, -1.0654047, 3.4175426, -2.0298796 };

            for (var i = 0; i < expectedX.Length; i++)
            {
                result.X[i].Should().BeApproximately(expectedX[i], GmresSolver.DefaultEpsilon);
            }
        }
Example #10
0
 public void CanReadFudao007AsComplex32()
 {
     using (TextReader reader = TestData.Data.ReadText("MatrixMarket.fidap007.mtx"))
     {
         var m = MatrixMarketReader.ReadMatrix <Complex32>(reader);
         Assert.IsInstanceOf <LinearAlgebra.Complex32.SparseMatrix>(m);
         Assert.AreEqual(1633, m.RowCount);
         Assert.AreEqual(1633, m.ColumnCount);
         Assert.GreaterOrEqual(54487, ((LinearAlgebra.Complex32.SparseMatrix)m).NonZerosCount);
         Assert.Less(46000, ((LinearAlgebra.Complex32.SparseMatrix)m).NonZerosCount);
         Assert.AreEqual(-6.8596032449032e+06f, m[1604, 1631].Real);
         Assert.AreEqual(0.0f, m[1604, 1631].Imaginary);
         Assert.AreEqual(-9.1914585107976e+06f, m[1616, 1628].Real);
         Assert.AreEqual(0.0f, m[1616, 1628].Imaginary);
         Assert.AreEqual(7.9403870156486e+07f, m[905, 726].Real);
         Assert.AreEqual(0.0f, m[905, 726].Imaginary);
     }
 }
Example #11
0
        private void Run(MatrixFile file, Stopwatch timer, List <BenchmarkResult> results)
        {
            string name = Path.GetFileName(file.Path);

            if (!File.Exists(file.Path))
            {
                results.Add(new BenchmarkResult(file, "File not found."));

                return;
            }

            try
            {
                var A = (CompressedColumnStorage <T>)file.Matrix;

                if (A == null)
                {
                    A = MatrixMarketReader.ReadMatrix <T>(file.Path);
                }

                int columns = A.ColumnCount;

                var x = CreateTestVector(columns);
                var s = CreateTestVector(columns);
                var b = new T[A.RowCount];

                A.Multiply(x, b);

                Array.Clear(x, 0, columns);

                var info = new BenchmarkResult(file, A.RowCount, columns, GetNonZerosCount(A));

                info.Time = Solve(A, b, x, file.Symmetric, timer);

                info.Residual = ComputeError(x, s);

                results.Add(info);
            }
            catch (Exception e)
            {
                results.Add(new BenchmarkResult(file, e.Message));
            }
        }
        private static void TestNormalEquationsSolution()
        {
            // Load a regtangular matrix from a file.
            string filePath = null;
            var    A        = MatrixMarketReader.ReadMatrix <double>(filePath);

            int m = A.RowCount;
            int n = A.ColumnCount;

            // Create test data.
            var x = CSparse.Double.Vector.Create(n, 1.0);
            var b = new double[m];

            // Compute right hand side vector b.
            A.Multiply(1.0, x, 0.0, b);

            // Apply column ordering to A to reduce fill-in.
            var order = ColumnOrdering.MinimumDegreeAtPlusA;

            if (m > n)
            {
                var At  = A.Transpose();
                var AtA = At.Multiply(A);

                var c = CSparse.Double.Vector.Create(n, 0.0);

                At.Multiply(b, c);

                var chol = SparseCholesky.Create(AtA, order);

                // Solve normal equation A'Ax = A'b (overwrite x).
                chol.Solve(c, x);
            }
            else
            {
                Assert.True(false);
            }

            // Compute residual b - Ax (overwrite b).
            A.Multiply(-1.0, x, 1.0, b);
        }
Example #13
0
        public void TestWriteSparseSymmetric()
        {
            var A = SparseMatrix.OfColumnMajor(3, 3, new double[]
            {
                1.0, 0.0, 0.5,
                0.0, 2.0, 0.1,
                0.5, 0.1, 3.0,
            });

            using (var stream = new MemoryStream(256))
                using (var writer = new StreamWriter(stream, leaveOpen: true))
                {
                    MatrixMarketWriter.WriteMatrix(writer, A, true);

                    stream.Position = 0;

                    var B = MatrixMarketReader.ReadMatrix <double>(stream);

                    Assert.IsTrue(A.Equals(B));
                }
        }
Example #14
0
        public static void Execute(Options options)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            Console.WriteLine($"Reading from {options.InputMatrixFileName}...");
            var a = MatrixMarketReader.ReadMatrix <double>(options.InputMatrixFileName);

            Console.WriteLine($"Reading from {options.InputVectorFileName}...");
            var b = MatrixMarketReader.ReadVector <double>(options.InputVectorFileName);

            Console.WriteLine("Start solving...");
            var result = GmresSolver.Solve(a, b, options.MaxInnerIterations, options.MaxOuterIterations, options.Epsilon, degreeOfParallelism: options.DegreeOfParallelism);

            Console.WriteLine($"Finished. IsConverged = {result.IsConverged}. Last error: {result.Errors.Last()}");
            Console.WriteLine($"Performed {result.InnerIterations} inner iterations and {result.OuterIterations} outer iterations");

            Console.WriteLine($"Writing solution to {options.OutputFileName}...");
            MatrixMarketWriter.WriteVector(options.OutputFileName, result.X);

            Console.WriteLine($"Total execution time, ms: {stopwatch.Elapsed.TotalMilliseconds}");
        }
        public static void TestLinearSystemSolution()
        {
            // Load matrix from a file.
            var A = MatrixMarketReader.ReadMatrix <double>(PosDefMatrixPath);

            int m = A.RowCount;
            int n = A.ColumnCount;

            Assert.True(m == n);

            // Create test data.
            var xExpected = CSparse.Double.Vector.Create(n, 1.0);
            var b         = new double[m];

            // Compute right hand side vector b.
            A.Multiply(1.0, xExpected, 0.0, b);

            // Apply column ordering to A to reduce fill-in.
            var order = ColumnOrdering.MinimumDegreeAtPlusA;

            // Factorize
            var xComputed = new double[n];
            var chol      = SparseCholesky.Create(A, order);

            // Solve Ax = b (do not overwrite x).
            chol.Solve(b, xComputed);

            // Check the solution
            comparer.AssertEqual(xExpected, xComputed);


            // Compute residual b - Ax (do not overwrite b).
            var r = new double[m];

            Array.Copy(b, r, m);
            A.Multiply(-1.0, xComputed, 1.0, r);
        }
Example #16
0
        public static Matrix <double> createMatrixFromMatrixMarketFile(string path)
        {
            Matrix <double> matrix = Matrix <double> .Build.SparseOfMatrix(MatrixMarketReader.ReadMatrix <double>(path));

            return(matrix);
        }
Example #17
0
        public static IStorageAdapter LoadMatrix(string file)
        {
            var A = (SparseMatrix)MatrixMarketReader.ReadMatrix <Complex>(file);

            return(new SparseStorageAdapter(A));
        }