コード例 #1
0
        public void CanSolveForRandomMatrix(int order)
        {
            var matrixA = Matrix<double>.Build.Random(order, order, 1);
            var matrixB = Matrix<double>.Build.Random(order, order, 1);

            var monitor = new Iterator<double>(
                new IterationCountStopCriterium<double>(1000),
                new ResidualStopCriterium<double>(1e-10));

            var solver = new BiCgStab();
            var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);

            // The solution X row dimension is equal to the column dimension of A
            Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

            // The solution X has the same number of columns as B
            Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

            var matrixBReconstruct = matrixA*matrixX;

            // Check the reconstruction.
            for (var i = 0; i < matrixB.RowCount; i++)
            {
                for (var j = 0; j < matrixB.ColumnCount; j++)
                {
                    Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
                }
            }
        }
コード例 #2
0
        public void CanSolveForRandomVector(int order)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
            var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

            var monitor = new Iterator(new IIterationStopCriterium[]
            {
                new IterationCountStopCriterium(1000),
                new ResidualStopCriterium(1e-10),
            });
            var solver = new BiCgStab(monitor);

            var resultx = solver.Solve(matrixA, vectorb);

            Assert.AreEqual(matrixA.ColumnCount, resultx.Count);

            var matrixBReconstruct = matrixA * resultx;

            // Check the reconstruction.
            for (var i = 0; i < order; i++)
            {
                Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-5);
                Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-5);
            }
        }
コード例 #3
0
        public void CanSolveForRandomMatrix(int order)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
            var matrixB = MatrixLoader.GenerateRandomDenseMatrix(order, order);

            var monitor = new Iterator(new IIterationStopCriterium[]
            {
                new IterationCountStopCriterium(1000),
                new ResidualStopCriterium(1e-10)
            });
            var solver  = new BiCgStab(monitor);
            var matrixX = solver.Solve(matrixA, matrixB);

            // The solution X row dimension is equal to the column dimension of A
            Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

            // The solution X has the same number of columns as B
            Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

            var matrixBReconstruct = matrixA * matrixX;

            // Check the reconstruction.
            for (var i = 0; i < matrixB.RowCount; i++)
            {
                for (var j = 0; j < matrixB.ColumnCount; j++)
                {
                    Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
                }
            }
        }
コード例 #4
0
        public void CanSolveForRandomVector(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterion each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = Matrix <float> .Build.Random(order, order, 1);

                var vectorb = Vector <float> .Build.Random(order, 1);

                var monitor = new Iterator <float>(
                    new IterationCountStopCriterion <float>(MaximumIterations),
                    new ResidualStopCriterion <float>(Math.Pow(1.0 / 10.0, iteration)));

                var solver  = new BiCgStab();
                var resultx = matrixA.SolveIterative(vectorb, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA * resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i], matrixBReconstruct[i], (float)Math.Pow(1.0 / 10.0, iteration - 3));
                }

                return;
            }
        }
コード例 #5
0
        public void CanSolveForRandomMatrix(int order)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
            var matrixB = MatrixLoader.GenerateRandomDenseMatrix(order, order);

            var monitor = new Iterator(new IIterationStopCriterium[]
                                       {
                                           new IterationCountStopCriterium(1000),
                                           new ResidualStopCriterium(1e-10)
                                       });
            var solver = new BiCgStab(monitor);
            var matrixX = solver.Solve(matrixA, matrixB);

            // The solution X row dimension is equal to the column dimension of A
            Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

            // The solution X has the same number of columns as B
            Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

            var matrixBReconstruct = matrixA * matrixX;

            // Check the reconstruction.
            for (var i = 0; i < matrixB.RowCount; i++)
            {
                for (var j = 0; j < matrixB.ColumnCount; j++)
                {
                    Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
                }
            }
        }
コード例 #6
0
        public void CanSolveForRandomMatrix(int order)
        {
            var matrixA = Matrix <double> .Build.Random(order, order, 100);

            var matrixB = Matrix <double> .Build.Random(order, order, 200);

            var monitor = new Iterator <double>(
                new IterationCountStopCriterion <double>(1000),
                new ResidualStopCriterion <double>(1e-10));

            var solver  = new BiCgStab();
            var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);

            // The solution X row dimension is equal to the column dimension of A
            Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

            // The solution X has the same number of columns as B
            Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

            var matrixBReconstruct = matrixA * matrixX;

            // Check the reconstruction.
            for (var i = 0; i < matrixB.RowCount; i++)
            {
                for (var j = 0; j < matrixB.ColumnCount; j++)
                {
                    Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
                }
            }
        }
コード例 #7
0
        public void SolveLongMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(3, 2);
            var input = new DenseVector(3);

            var solver = new BiCgStab();
            Assert.Throws<ArgumentException>(() => matrix.SolveIterative(input, solver));
        }
コード例 #8
0
        public void SolveWideMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(2, 3);
            var input = new DenseVector(2);

            var solver = new BiCgStab();
            Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
        }
コード例 #9
0
        public void SolveLongMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(3, 2);
            Vector input = new DenseVector(3);

            var solver = new BiCgStab();
            Assert.Throws<ArgumentException>(() => solver.Solve(matrix, input));
        }
コード例 #10
0
        public void SolveLongMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(3, 2);
            var input  = new DenseVector(3);

            var solver = new BiCgStab();

            Assert.Throws <ArgumentException>(() => solver.Solve(matrix, input));
        }
コード例 #11
0
        public void SolveLongMatrix()
        {
            var             matrix = new SparseMatrix(3, 2);
            Vector <double> input  = new DenseVector(3);

            var solver = new BiCgStab();

            solver.Solve(matrix, input);
        }
        public void SolveWideMatrix()
        {
            var matrix = new SparseMatrix(2, 3);
            Vector <Complex32> input = new DenseVector(2);

            var solver = new BiCgStab();

            solver.Solve(matrix, input);
        }
コード例 #13
0
        public void SolveLongMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(3, 2);
            var input  = new DenseVector(3);

            var solver = new BiCgStab();

            Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
        }
コード例 #14
0
        public void SolveWideMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(2, 3);
            var input  = new DenseVector(2);

            var solver = new BiCgStab();

            Assert.Throws <ArgumentException>(() => matrix.SolveIterative(input, solver));
        }
コード例 #15
0
ファイル: BicgStab.cs プロジェクト: alexflorea/CN
        /// <summary>
        /// The main method that runs the BiCGStab iterative solver.
        /// </summary>
        public void UseSolver()
        {
            // Create a sparse matrix. For now the size will be 10 x 10 elements
            Matrix matrix = CreateMatrix(10);

            // Create the right hand side vector. The size is the same as the matrix
            // and all values will be 2.0.
            Vector rightHandSideVector = new DenseVector(10, 2.0);

            // Create a preconditioner. The possibilities are:
            // 1) No preconditioner - Simply do not provide the solver with a preconditioner.
            // 2) A simple diagonal preconditioner - Create an instance of the Diagonal class.
            // 3) A ILU preconditioner - Create an instance of the IncompleteLu class.
            // 4) A ILU preconditioner with pivoting and drop tolerances - Create an instance of the Ilutp class.

            // Here we'll use the simple diagonal preconditioner.
            // We need a link to the matrix so the pre-conditioner can do it's work.
            IPreConditioner preconditioner = new Diagonal();

            // Create a new iterator. This checks for convergence of the results of the
            // iterative matrix solver.
            // In this case we'll create the default iterator
            IIterator iterator = Iterator.CreateDefault();

            // Create the solver
            BiCgStab solver = new BiCgStab(preconditioner, iterator);

            // Now that all is set we can solve the matrix equation.
            Vector solutionVector = solver.Solve(matrix, rightHandSideVector);

            // Another way to get the values is by using the overloaded solve method
            // In this case the solution vector needs to be of the correct size.
            solver.Solve(matrix, rightHandSideVector, solutionVector);

            // Finally you can check the reason the solver finished the iterative process
            // by calling the SolutionStatus property on the iterator
            ICalculationStatus status = iterator.Status;
            if (status is CalculationCancelled)
                Console.WriteLine("The user cancelled the calculation.");

            if (status is CalculationIndetermined)
                Console.WriteLine("Oh oh, something went wrong. The iterative process was never started.");

            if (status is CalculationConverged)
                Console.WriteLine("Yippee, the iterative process converged.");

            if (status is CalculationDiverged)
                Console.WriteLine("I'm sorry the iterative process diverged.");

            if (status is CalculationFailure)
                Console.WriteLine("Oh dear, the iterative process failed.");

            if (status is CalculationStoppedWithoutConvergence)
                Console.WriteLine("Oh dear, the iterative process did not converge.");
        }
コード例 #16
0
        private Complex[] CalculateSystemOfLinearEquations(Complex[,] matrixSystem, Complex[] matrixRightSide)
        {
            var matrixA = DenseMatrix.OfArray(matrixSystem);
            var vectorB = new DenseVector(matrixRightSide);
            var iterationCountStopCriterion = new IterationCountStopCriterion <Complex>(1000);
            var residualStopCriterion       = new ResidualStopCriterion <Complex>(1e-10);
            var monitor = new Iterator <Complex>(iterationCountStopCriterion, residualStopCriterion);
            var solver  = new BiCgStab();

            return(matrixA.SolveIterative(vectorB, solver, monitor).ToArray());
        }
コード例 #17
0
        // Method to set up parameters for iterative solver
        // Code for this method taken from the lecture slides (Lectures 5 and 6, solving 1D Heat Equation)
        private void SetUpSolver()
        {
            // Stop after 1000 iterations
            IterationCountStopCriterion <double> iterationCountStopCriterion
                = new IterationCountStopCriterion <double>(1000);

            // Stop after the error is less than 1e-8
            ResidualStopCriterion <double> residualStopCriterion
                = new ResidualStopCriterion <double>(1e-8);

            monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);
            solver  = new BiCgStab();
        }
コード例 #18
0
        //Method to set up parameters for iterative solver
        private void SetUpSolver()
        {
            // Stop calculation if 1000 iterations reached during calculation
            IterationCountStopCriterion <double> iterationCountStopCriterion
                = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1e-8
            // i.e. the calculation is considered converged
            ResidualStopCriterion <double> residualStopCriterion
                = new ResidualStopCriterion <double>(1e-8);

            // Create monitor with defined stop criteria
            monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);
            solver  = new BiCgStab();
        }
コード例 #19
0
    private void SetUpSolver()
    {
        // Stop calculation if 1000 iterations reached during calculation
        IterationCountStopCriterion <double> iterationCountStopCriterion = new IterationCountStopCriterion <double>(100);

        // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
        ResidualStopCriterion <double> residualStopCriterion = new ResidualStopCriterion <double>(1e-8);

        // Create monitor with defined stop criteria
        monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

        // Load all suitable solvers from current assembly. Below in this example, there is user-defined solver
        // "class UserBiCgStab : IIterativeSolverSetup<double>" which uses regular BiCgStab solver. But user may create any other solver
        // and solver setup classes which implement IIterativeSolverSetup<T> and pass assembly to next function:
        solver = new BiCgStab();
    }
コード例 #20
0
        public void solve()
        {
            Matrix <float> A = null;
            Vector <float> b = null;
            Vector <float> x = null;

            IIterationStopCriterion <float> count_stop_criterion    = new IterationCountStopCriterion <float>(5000);
            IIterationStopCriterion <float> residual_stop_criterion = new ResidualStopCriterion <float>(1e-10f);
            Iterator <float>        iterator       = new Iterator <float>(count_stop_criterion, residual_stop_criterion);
            IPreconditioner <float> preconditioner = null;



            BiCgStab solver = new BiCgStab();

            solver.Solve(A, b, x, iterator, preconditioner);
        }
コード例 #21
0
        public void CanSolveForRandomMatrix(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterium each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var matrixB = MatrixLoader.GenerateRandomDenseMatrix(order, order);

                var monitor = new Iterator(new IIterationStopCriterium <float>[]
                {
                    new IterationCountStopCriterium(MaximumIterations),
                    new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration))
                });
                var solver  = new BiCgStab(monitor);
                var matrixX = solver.Solve(matrixA, matrixB);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA * matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreApproximatelyEqual(matrixB[i, j], matrixBReconstruct[i, j], (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    }
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #22
0
        public void CanSolveForRandomMatrix(int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var matrixB = MatrixLoader.GenerateRandomDenseMatrix(order, order);

                var monitor = new Iterator(new IIterationStopCriterium <Complex32>[]
                {
                    new IterationCountStopCriterium <Complex32>(1000),
                    new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration))
                });
                var solver  = new BiCgStab(monitor);
                var matrixX = solver.Solve(matrixA, matrixB);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA * matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                        Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    }
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #23
0
        public void CanSolveForRandomMatrix(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterium each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var matrixB = MatrixLoader.GenerateRandomDenseMatrix(order, order);

                var monitor = new Iterator(new IIterationStopCriterium<float>[]
                                           {
                                               new IterationCountStopCriterium(MaximumIterations),
                                               new ResidualStopCriterium((float)Math.Pow(1.0/10.0, iteration))
                                           });
                var solver = new BiCgStab(monitor);
                var matrixX = solver.Solve(matrixA, matrixB);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA * matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreApproximatelyEqual(matrixB[i, j], matrixBReconstruct[i, j], (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    }
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #24
0
        public void CanSolveForRandomMatrix([Values(4)] int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var matrixB = MatrixLoader.GenerateRandomDenseMatrix(order, order);

                var monitor = new Iterator(new IIterationStopCriterium[]
                                           {
                                               new IterationCountStopCriterium(1000),
                                               new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration))
                                           });
                var solver = new BiCgStab(monitor);
                var matrixX = solver.Solve(matrixA, matrixB);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA * matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                        Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    }
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #25
0
        public void CanSolveForRandomMatrix(int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
                var matrixB = Matrix<Complex32>.Build.Random(order, order, 1);

                var monitor = new Iterator<Complex32>(
                    new IterationCountStopCriterion<Complex32>(1000),
                    new ResidualStopCriterion<Complex32>(Math.Pow(1.0/10.0, iteration)));

                var solver = new BiCgStab();
                var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA*matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, (float)Math.Pow(1.0/10.0, iteration - 3));
                        Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, (float)Math.Pow(1.0/10.0, iteration - 3));
                    }
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #26
0
        public void CanSolveForRandomMatrix(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterion each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = Matrix <float> .Build.Random(order, order, 1);

                var matrixB = Matrix <float> .Build.Random(order, order, 1);

                var monitor = new Iterator <float>(
                    new IterationCountStopCriterion <float>(MaximumIterations),
                    new ResidualStopCriterion <float>(Math.Pow(1.0 / 10.0, iteration)));

                var solver  = new BiCgStab();
                var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA * matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    }
                }

                return;
            }
        }
コード例 #27
0
        public void CanSolveForRandomMatrix(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterion each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = Matrix<float>.Build.Random(order, order, 1);
                var matrixB = Matrix<float>.Build.Random(order, order, 1);

                var monitor = new Iterator<float>(
                    new IterationCountStopCriterion<float>(MaximumIterations),
                    new ResidualStopCriterion<float>(Math.Pow(1.0/10.0, iteration)));

                var solver = new BiCgStab();
                var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                // The solution X row dimension is equal to the column dimension of A
                Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);

                // The solution X has the same number of columns as B
                Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);

                var matrixBReconstruct = matrixA*matrixX;

                // Check the reconstruction.
                for (var i = 0; i < matrixB.RowCount; i++)
                {
                    for (var j = 0; j < matrixB.ColumnCount; j++)
                    {
                        Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], (float)Math.Pow(1.0/10.0, iteration - 3));
                    }
                }

                return;
            }
        }
コード例 #28
0
        public void SolveScaledUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            var matrix = SparseMatrix.Identity(100);

            // Scale it with a funny number
            matrix.Multiply((float)Math.PI, matrix);

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, i => 1);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator(new IIterationStopCriterium <float>[]
            {
                new IterationCountStopCriterium <float>(MaximumIterations),
                new ResidualStopCriterium(ConvergenceBoundary),
                new DivergenceStopCriterium(),
                new FailureStopCriterium()
            });
            var solver = new BiCgStab(monitor);

            // Solve equation Ax = y
            var x = solver.Solve(matrix, y);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status is CalculationConverged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.IsTrue((y[i] - z[i]).IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
            }
        }
コード例 #29
0
        public void SolveScaledUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            var matrix = Matrix <double> .Build.SparseIdentity(100);

            // Scale it with a funny number
            matrix.Multiply(Math.PI, matrix);

            // Create the y vector
            var y = Vector <double> .Build.Dense(matrix.RowCount, 1);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator <double>(
                new IterationCountStopCriterion <double>(MaximumIterations),
                new ResidualStopCriterion <double>(ConvergenceBoundary),
                new DivergenceStopCriterion <double>(),
                new FailureStopCriterion <double>());

            var solver = new BiCgStab();

            // Solve equation Ax = y
            var x = matrix.SolveIterative(y, solver, monitor);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
            }
        }
コード例 #30
0
ファイル: Simulation.cs プロジェクト: soulcyon/decaf2.5
        public static double CalculateSsu()
        {
            // Stopwatch start
            Timer.Restart();
            var evector = new DenseVector(Length);

            for (var i = 0; i < Length; i++)
            {
                QMatrix[i, 0] = 1;
                evector[i]    = 0;
            }
            evector[0] = 1.0;
            var qtilde = new SparseMatrix(QMatrix.Transpose().ToArray());

            var v      = new BiCgStab().Solve(qtilde, evector);
            var result = v.Sum() - UpStates.Sum(i => v[i]);

            // Stopwatch stop and store statistic
            _timeToSSU = (ulong)Timer.ElapsedTicks;
            Timer.Stop();

            return(result);
        }
コード例 #31
0
        public void CanSolveForRandomVector(int order)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
            var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

            var monitor = new Iterator <double>(
                new IterationCountStopCriterium <double>(1000),
                new ResidualStopCriterium <double>(1e-10));

            var solver = new BiCgStab();

            var resultx = matrixA.SolveIterative(vectorb, solver, monitor);

            Assert.AreEqual(matrixA.ColumnCount, resultx.Count);

            var matrixBReconstruct = matrixA * resultx;

            // Check the reconstruction.
            for (var i = 0; i < order; i++)
            {
                Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-7);
            }
        }
コード例 #32
0
        public void CanSolveForRandomVector(int order)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
            var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

            var monitor = new Iterator(new IIterationStopCriterium<double>[]
                                       {
                                           new IterationCountStopCriterium(1000),
                                           new ResidualStopCriterium(1e-10),
                                       });
            var solver = new BiCgStab(monitor);

            var resultx = solver.Solve(matrixA, vectorb);
            Assert.AreEqual(matrixA.ColumnCount, resultx.Count);

            var bReconstruct = matrixA * resultx;

            // Check the reconstruction.
            for (var i = 0; i < order; i++)
            {
                Assert.AreApproximatelyEqual(vectorb[i], bReconstruct[i], 1e-7);
            }
        }
コード例 #33
0
        public void CanSolveForRandomVector(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterium each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

                var monitor = new Iterator(new IIterationStopCriterium <float>[]
                {
                    new IterationCountStopCriterium(MaximumIterations),
                    new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration)),
                });
                var solver  = new BiCgStab(monitor);
                var resultx = solver.Solve(matrixA, vectorb);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var bReconstruct = matrixA * resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreApproximatelyEqual(vectorb[i], bReconstruct[i], (float)Math.Pow(1.0 / 10.0, iteration - 3));
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #34
0
        public void CanSolveForRandomVector(int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = Matrix <Complex32> .Build.Random(order, order, 1);

                var vectorb = Vector <Complex32> .Build.Random(order, 1);

                var monitor = new Iterator <Complex32>(
                    new IterationCountStopCriterion <Complex32>(1000),
                    new ResidualStopCriterion <Complex32>(Math.Pow(1.0 / 10.0, iteration)));

                var solver = new BiCgStab();

                var resultx = matrixA.SolveIterative(vectorb, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA * resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #35
0
        public void CanSolveForRandomVector(int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

                var monitor = new Iterator(new IIterationStopCriterium <Complex32>[]
                {
                    new IterationCountStopCriterium <Complex32>(1000),
                    new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration)),
                });
                var solver = new BiCgStab(monitor);

                var resultx = solver.Solve(matrixA, vectorb);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA * resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #36
0
        public void SolveUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            var matrix = SparseMatrix.CreateIdentity(100);

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, Complex.One);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator <Complex>(
                new IterationCountStopCriterion <Complex>(MaximumIterations),
                new ResidualStopCriterion <Complex>(ConvergenceBoundary),
                new DivergenceStopCriterion <Complex>(),
                new FailureStopCriterion <Complex>());

            var solver = new BiCgStab();

            // Solve equation Ax = y
            var x = matrix.SolveIterative(y, solver, monitor);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
            }
        }
コード例 #37
0
        public void SolvePoissonMatrixAndBackMultiply()
        {
            // Create the matrix
            var matrix = new SparseMatrix(100);

            // Assemble the matrix. We assume we're solving the Poisson equation
            // on a rectangular 10 x 10 grid
            const int GridSize = 10;

            // The pattern is:
            // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
            for (var i = 0; i < matrix.RowCount; i++)
            {
                // Insert the first set of -1's
                if (i > (GridSize - 1))
                {
                    matrix[i, i - GridSize] = -1;
                }

                // Insert the second set of -1's
                if (i > 0)
                {
                    matrix[i, i - 1] = -1;
                }

                // Insert the centerline values
                matrix[i, i] = 4;

                // Insert the first trailing set of -1's
                if (i < matrix.RowCount - 1)
                {
                    matrix[i, i + 1] = -1;
                }

                // Insert the second trailing set of -1's
                if (i < matrix.RowCount - GridSize)
                {
                    matrix[i, i + GridSize] = -1;
                }
            }

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, Complex.One);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator <Complex>(new IterationCountStopCriterion <Complex>(MaximumIterations),
                                                 new ResidualStopCriterion <Complex>(ConvergenceBoundary),
                                                 new DivergenceStopCriterion <Complex>(),
                                                 new FailureStopCriterion <Complex>());

            var solver = new BiCgStab();

            // Solve equation Ax = y
            var x = matrix.SolveIterative(y, solver, monitor);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
            }
        }
コード例 #38
0
        /// <summary>
        /// Run example
        /// </summary>
        /// <seealso cref="http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method">Biconjugate gradient stabilized method</seealso>
        public void Run()
        {
            // Format matrix output to console
            var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();
            formatProvider.TextInfo.ListSeparator = " ";

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            var matrixA = DenseMatrix.OfArray(new[,] { { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 } });
            Console.WriteLine(@"Matrix 'A' with coefficients");
            Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create vector "b" with the constant terms.
            var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
            Console.WriteLine(@"Vector 'b' with the constant terms");
            Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
            // - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterium: monitors residuals for NaN's;
            // - IterationCountStopCriterium: monitors the numbers of iteration steps;
            // - ResidualStopCriterium: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            var iterationCountStopCriterium = new IterationCountStopCriterium<double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            var residualStopCriterium = new ResidualStopCriterium<double>(1e-10);

            // Create monitor with defined stop criteriums
            var monitor = new Iterator<double>(iterationCountStopCriterium, residualStopCriterium);

            // Create Bi-Conjugate Gradient Stabilized solver
            var solver = new BiCgStab();

            // 1. Solve the matrix equation
            var resultX = matrixA.SolveIterative(vectorB, solver, monitor);
            Console.WriteLine(@"1. Solve the matrix equation");
            Console.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            Console.WriteLine(@"2. Solver status of the iterations");
            Console.WriteLine(monitor.Status);
            Console.WriteLine();

            // 3. Solution result vector of the matrix equation
            Console.WriteLine(@"3. Solution result vector of the matrix equation");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            var reconstructVecorB = matrixA * resultX;
            Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();
        }
コード例 #39
0
        public void CanSolveForRandomVector([Values(4)] int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

                var monitor = new Iterator(new IIterationStopCriterium[]
                                           {
                                               new IterationCountStopCriterium(1000), 
                                               new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration)), 
                                           });
                var solver = new BiCgStab(monitor);

                var resultx = solver.Solve(matrixA, vectorb);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA * resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #40
0
        public void CanSolveForRandomVector(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterium each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

                var monitor = new Iterator(new IIterationStopCriterium[]
                    {
                        new IterationCountStopCriterium(MaximumIterations),
                        new ResidualStopCriterium((float) Math.Pow(1.0/10.0, iteration)),
                    });
                var solver = new BiCgStab(monitor);
                var resultx = solver.Solve(matrixA, vectorb);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA*resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i], matrixBReconstruct[i], (float) Math.Pow(1.0/10.0, iteration - 3));
                }

                return;
            }
        }
コード例 #41
0
        public override void ExecuteExample()
        {
            // <seealso cref="http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method">Biconjugate gradient stabilized method</seealso>
            MathDisplay.WriteLine("<b>Biconjugate gradient stabilised iterative solver</b>");

            // Format matrix output to console
            var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();

            formatProvider.TextInfo.ListSeparator = " ";

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            var matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });

            MathDisplay.WriteLine(@"Matrix 'A' with coefficients");
            MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create vector "b" with the constant terms.
            var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });

            MathDisplay.WriteLine(@"Vector 'b' with the constant terms");
            MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create stop criteria to monitor an iterative calculation. There are next available stop criteria:
            // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterion: monitors residuals for NaN's;
            // - IterationCountStopCriterion: monitors the numbers of iteration steps;
            // - ResidualStopCriterion: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            var iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            var residualStopCriterion = new ResidualStopCriterion <double>(1e-10);

            // Create monitor with defined stop criteria
            var monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

            // Create Bi-Conjugate Gradient Stabilized solver
            var solverBiCgStab = new BiCgStab();

            // 1. Solve the matrix equation
            var resultX = matrixA.SolveIterative(vectorB, solverBiCgStab, monitor);

            MathDisplay.WriteLine(@"1. Solve the matrix equation");
            MathDisplay.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            MathDisplay.WriteLine(@"2. Solver status of the iterations");
            MathDisplay.WriteLine(monitor.Status.ToString());
            MathDisplay.WriteLine();

            // 3. Solution result vector of the matrix equation
            MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation");
            MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            var reconstructVecorB = matrixA * resultX;

            MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();



            MathDisplay.WriteLine("<b>Generalized product biconjugate gradient solver</b>");

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });
            MathDisplay.WriteLine(@"Matrix 'A' with coefficients");
            MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create vector "b" with the constant terms.
            vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
            MathDisplay.WriteLine(@"Vector 'b' with the constant terms");
            MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create stop criteria to monitor an iterative calculation. There are next available stop criteria:
            // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterion: monitors residuals for NaN's;
            // - IterationCountStopCriterion: monitors the numbers of iteration steps;
            // - ResidualStopCriterion: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            residualStopCriterion = new ResidualStopCriterion <double>(1e-10);

            // Create monitor with defined stop criteria
            monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

            // Create Generalized Product Bi-Conjugate Gradient solver
            var solverGpBiCg = new GpBiCg();

            // 1. Solve the matrix equation
            resultX = matrixA.SolveIterative(vectorB, solverGpBiCg, monitor);
            MathDisplay.WriteLine(@"1. Solve the matrix equation");
            MathDisplay.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            MathDisplay.WriteLine(@"2. Solver status of the iterations");
            MathDisplay.WriteLine(monitor.Status.ToString());
            MathDisplay.WriteLine();

            // 3. Solution result vector of the matrix equation
            MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation");
            MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            reconstructVecorB = matrixA * resultX;
            MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Composite linear equation solver</b>");

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });
            MathDisplay.WriteLine(@"Matrix 'A' with coefficients");
            MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create vector "b" with the constant terms.
            vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
            MathDisplay.WriteLine(@"Vector 'b' with the constant terms");
            MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create stop criteria to monitor an iterative calculation. There are next available stop criteria:
            // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterion: monitors residuals for NaN's;
            // - IterationCountStopCriterion: monitors the numbers of iteration steps;
            // - ResidualStopCriterion: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            residualStopCriterion = new ResidualStopCriterion <double>(1e-10);

            // Create monitor with defined stop criteria
            monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

            // Load all suitable solvers from current assembly. Below (see UserBiCgStab) there is a custom user-defined solver
            // "class UserBiCgStab : IIterativeSolverSetup<double>" which derives from the regular BiCgStab solver. However users can
            // create any other solver and solver setup classes that implement IIterativeSolverSetup<T> and load the assembly that
            // contains them using the following function:
            var solverComp = new CompositeSolver(SolverSetup <double> .LoadFromAssembly(Assembly.GetExecutingAssembly()));

            // 1. Solve the linear system
            resultX = matrixA.SolveIterative(vectorB, solverComp, monitor);
            MathDisplay.WriteLine(@"1. Solve the matrix equation");
            MathDisplay.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            MathDisplay.WriteLine(@"2. Solver status of the iterations");
            MathDisplay.WriteLine(monitor.Status.ToString());
            MathDisplay.WriteLine();

            // 3. Solution result vector of the matrix equation
            MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation");
            MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            reconstructVecorB = matrixA * resultX;
            MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Multiple-Lanczos biconjugate gradient stabilised iterative solver</b>");

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });
            MathDisplay.WriteLine(@"Matrix 'A' with coefficients");
            MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create vector "b" with the constant terms.
            vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
            MathDisplay.WriteLine(@"Vector 'b' with the constant terms");
            MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create stop criteria to monitor an iterative calculation. There are next available stop criteria:
            // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterion: monitors residuals for NaN's;
            // - IterationCountStopCriterion: monitors the numbers of iteration steps;
            // - ResidualStopCriterion: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            residualStopCriterion = new ResidualStopCriterion <double>(1e-10);

            // Create monitor with defined stop criteria
            monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

            // Create Multiple-Lanczos Bi-Conjugate Gradient Stabilized solver
            var solverLanczos = new MlkBiCgStab();

            // 1. Solve the matrix equation
            resultX = matrixA.SolveIterative(vectorB, solverLanczos, monitor);
            MathDisplay.WriteLine(@"1. Solve the matrix equation");
            MathDisplay.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            MathDisplay.WriteLine(@"2. Solver status of the iterations");
            MathDisplay.WriteLine(monitor.Status.ToString());
            MathDisplay.WriteLine();

            // 3. Solution result vector of the matrix equation
            MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation");
            MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            reconstructVecorB = matrixA * resultX;
            MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();


            MathDisplay.WriteLine("<b>Transpose freee quasi-minimal residual iterative solver</b>");

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });
            MathDisplay.WriteLine(@"Matrix 'A' with coefficients");
            MathDisplay.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create vector "b" with the constant terms.
            vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });
            MathDisplay.WriteLine(@"Vector 'b' with the constant terms");
            MathDisplay.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // Create stop criteria to monitor an iterative calculation. There are next available stop criteria:
            // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterion: monitors residuals for NaN's;
            // - IterationCountStopCriterion: monitors the numbers of iteration steps;
            // - ResidualStopCriterion: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            residualStopCriterion = new ResidualStopCriterion <double>(1e-10);

            // Create monitor with defined stop criteria
            monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

            // Create Transpose Free Quasi-Minimal Residual solver
            var solverTFQMR = new TFQMR();

            // 1. Solve the matrix equation
            resultX = matrixA.SolveIterative(vectorB, solverTFQMR, monitor);
            MathDisplay.WriteLine(@"1. Solve the matrix equation");
            MathDisplay.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            MathDisplay.WriteLine(@"2. Solver status of the iterations");
            MathDisplay.WriteLine(monitor.Status.ToString());
            MathDisplay.WriteLine();

            // 3. Solution result vector of the matrix equation
            MathDisplay.WriteLine(@"3. Solution result vector of the matrix equation");
            MathDisplay.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            reconstructVecorB = matrixA * resultX;
            MathDisplay.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            MathDisplay.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            MathDisplay.WriteLine();
        }
コード例 #42
0
ファイル: Base2.cs プロジェクト: Madu86/HPM
        public static void MinimizeDivergence()
        {
            CalculateGradients();

            CreateWindArrays();

            CreateTCWindArrays();

            CreateLambda();

            FillMatrixA();

            //#region ---Load MS Excel and write A---
            //Excel.Application oExcel = new Excel.Application { Visible = true };

            //oExcel.Workbooks.Add();
            //Excel._Worksheet workSheet = oExcel.ActiveSheet;

            //var arrA = A;


            //for (int i = 0; i < (Meteorology.NumberOfMetCellsX * Meteorology.NumberOfMetCellsY * Meteorology.NumberOfMetCellsZ); i++)
            //{

            //    for (excelColumnNumber = 0; excelColumnNumber < (Meteorology.NumberOfMetCellsX * Meteorology.NumberOfMetCellsY * Meteorology.NumberOfMetCellsZ); excelColumnNumber++)
            //    {

            //        workSheet.Cells[i + 1, excelColumnNumber + 1] = arrA[i, excelColumnNumber];

            //    }

            //}

            //#endregion



            BiCgStab b = new BiCgStab();

            b.SetIterator(dnAnalytics.LinearAlgebra.Solvers.Iterator.CreateDefault());
            b.SetPreconditioner(new Diagonal());

            bool divergenceMinimized = false;

            for (int p = 0; p < 50000; p++)
            {
                CalculateDivergence();

                double count = 0;
                foreach (double d in B.ToArray())
                {
                    count += 1;
                    if (-d > minimumDivergence)
                    {
                        break;
                    }
                    else if (count == B.Count)
                    {
                        divergenceMinimized = true;
                        break;
                    }
                }

                if (divergenceMinimized)
                {
                    break;
                }
                else
                {
                    var M = b.Solve(A, B);

                    for (int i = 0; i < M.Count; i++)
                    {
                        Lambda[i] = M[i];
                    }

                    UpdateWindArrays();
                }
            }



            CalculateCartesianWindComponents();

            UpdateMeteorology();
        }
コード例 #43
0
        public void CanSolveForRandomVector(int order)
        {
            // Due to datatype "float" it can happen that solution will not converge for specific random matrix
            // That's why we will do 3 tries and downgrade stop criterion each time
            for (var iteration = 6; iteration > 3; iteration--)
            {
                var matrixA = Matrix<float>.Build.Random(order, order, 1);
                var vectorb = Vector<float>.Build.Random(order, 1);

                var monitor = new Iterator<float>(
                    new IterationCountStopCriterion<float>(MaximumIterations),
                    new ResidualStopCriterion<float>(Math.Pow(1.0/10.0, iteration)));

                var solver = new BiCgStab();
                var resultx = matrixA.SolveIterative(vectorb, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA*resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i], matrixBReconstruct[i], (float)Math.Pow(1.0/10.0, iteration - 3));
                }

                return;
            }
        }
コード例 #44
0
        /// <summary>
        /// Run example
        /// </summary>
        /// <seealso cref="http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method">Biconjugate gradient stabilized method</seealso>
        public void Run()
        {
            // Format matrix output to console
            var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();

            formatProvider.TextInfo.ListSeparator = " ";

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            var matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });

            Console.WriteLine(@"Matrix 'A' with coefficients");
            Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create vector "b" with the constant terms.
            var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });

            Console.WriteLine(@"Vector 'b' with the constant terms");
            Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create stop criteria to monitor an iterative calculation. There are next available stop criteria:
            // - DivergenceStopCriterion: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterion: monitors residuals for NaN's;
            // - IterationCountStopCriterion: monitors the numbers of iteration steps;
            // - ResidualStopCriterion: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            var iterationCountStopCriterion = new IterationCountStopCriterion <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            var residualStopCriterion = new ResidualStopCriterion <double>(1e-10);

            // Create monitor with defined stop criteria
            var monitor = new Iterator <double>(iterationCountStopCriterion, residualStopCriterion);

            // Create Bi-Conjugate Gradient Stabilized solver
            var solver = new BiCgStab();

            // 1. Solve the matrix equation
            var resultX = matrixA.SolveIterative(vectorB, solver, monitor);

            Console.WriteLine(@"1. Solve the matrix equation");
            Console.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            Console.WriteLine(@"2. Solver status of the iterations");
            Console.WriteLine(monitor.Status);
            Console.WriteLine();

            // 3. Solution result vector of the matrix equation
            Console.WriteLine(@"3. Solution result vector of the matrix equation");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            var reconstructVecorB = matrixA * resultX;

            Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();
        }
コード例 #45
0
        public void SolveScaledUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            var matrix = SparseMatrix.Identity(100);

            // Scale it with a funny number
            matrix.Multiply(new Complex32((float) Math.PI, (float) Math.PI), matrix);

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, i => Complex32.One);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator<Complex32>(new IIterationStopCriterium<Complex32>[]
                {
                    new IterationCountStopCriterium<Complex32>(MaximumIterations),
                    new ResidualStopCriterium(ConvergenceBoundary),
                    new DivergenceStopCriterium(),
                    new FailureStopCriterium()
                });
            var solver = new BiCgStab(monitor);

            // Solve equation Ax = y
            var x = solver.Solve(matrix, y);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.HasConverged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.IsTrue((y[i] - z[i]).Magnitude.IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
            }
        }
コード例 #46
0
        public void CanSolveForRandomVector(int order)
        {
            var matrixA = Matrix<double>.Build.Random(order, order, 1);
            var vectorb = Vector<double>.Build.Random(order, 1);

            var monitor = new Iterator<double>(
                new IterationCountStopCriterium<double>(1000),
                new ResidualStopCriterium<double>(1e-10));

            var solver = new BiCgStab();

            var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
            Assert.AreEqual(matrixA.ColumnCount, resultx.Count);

            var matrixBReconstruct = matrixA*resultx;

            // Check the reconstruction.
            for (var i = 0; i < order; i++)
            {
                Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-7);
            }
        }
コード例 #47
0
ファイル: Form1.cs プロジェクト: CommanderLee/DIPCourse
        /// <summary>
        /// Start Image Fusion
        /// Based on Poisson Image Editing. P Perez et. al. SIGGRAPH 2003
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonImageFusion_Click(object sender, EventArgs e)
        {
            if (zoomSrcImg != null && tarImg != null)
            {
                DateTime startTime = DateTime.Now;
                // Set the boundary value of zoomSrcImg
                pointId = new int [zoomSrcImg.Height, zoomSrcImg.Width];
                // +----------+
                // +          +
                // +----------+
                for (var r = 0; r < zoomSrcImg.Height; ++r)
                {
                    pointId[r, 0] = -1;
                    pointId[r, zoomSrcImg.Width - 1] = -1;
                }
                // -++++++++++-
                // -          -
                // -++++++++++-
                for (var c = 1; c < zoomSrcImg.Width - 1; ++c)
                {
                    pointId[0, c] = -1;
                    pointId[zoomSrcImg.Height - 1, c] = -1;
                }

                // Set mapping between point Id and the position
                List<Point> contentList = new List<Point>();
                for (var r = 1; r < zoomSrcImg.Height - 1; ++r)
                    for (var c = 1; c < zoomSrcImg.Width - 1; ++c)
                    {
                        pointId[r, c] = contentList.Count;
                        contentList.Add(new Point(r, c));
                    }
                Console.WriteLine("Mark every points with -1, 0, ...Time:" + DateTime.Now.Subtract(startTime).TotalSeconds);

                // Solve AX=B problem using solutions from the paper: Poisson Image Editing.
                int contentNum = contentList.Count;
                // To solve AX=B, get matrix A and B first
                //var matA = LA.Matrix<double>.Build.Sparse(contentNum, contentNum);
                //var matB = LA.Double.Vector.Build.Dense(contentNum);

                // top, right, bottom, left. In order to use for-loop.
                int[] dx = new int[] {-1, 0, 1, 0};
                int[] dy = new int[] { 0, 1, 0, -1 };

                Image<Bgr, byte> resultImg = imgList[currImgIdFusion].Copy();
                //int[,] contentColor = new int[3, contentNum];
                // Parallelize color channel B, G, R
                System.Threading.Tasks.Parallel.For(0, 3, (k) =>
                //for (var k = 0; k <= 2; ++k)
                {
                    Console.WriteLine("Generate Matrix No. " + k);

                    // Set matrix A & B to zero
                    var matA = LA.Matrix<double>.Build.Sparse(contentNum, contentNum);
                    var matB = LA.Double.Vector.Build.Dense(contentNum);
                    //matA.Clear();
                    //matB.Clear();

                    // Point P's neighbours.
                    List<Point> Np = new List<Point>();

                    // Generate matrix A & B
                    for (var id = 0; id < contentNum; ++id)
                    {
                        // For each point, use equation No.7 & No.8 in the paper
                        // Which means one row in the matrix

                        // Matrix A

                        Np.Clear();
                        // Old Point P: position in the zoomSrcImg. New Point P: position in the tarImg
                        Point oldP = contentList[id];
                        Point newP = new Point(oldP.X + tarTopLeftX, oldP.Y + tarTopLeftY);
                        for (var i = 0; i < 4; ++i)
                        {
                            // New Point Q: P's neighbour in the WHOLE target image
                            Point newQ = new Point(newP.X + dx[i], newP.Y + dy[i]);
                            if (newQ.X >= 0 && newQ.X < resultImg.Height && newQ.Y >= 0 && newQ.Y < resultImg.Width)
                            {
                                // Point Q is inside the area Omiga
                                Np.Add(newQ);
                            }
                        }
                        matA.At(id, id, Np.Count);

                        foreach (Point newQ in Np)
                        {
                            // Check Point Id of Old Q
                            int qID = pointId[newQ.X - tarTopLeftX, newQ.Y - tarTopLeftY];
                            // Old Q is inside Omiga
                            if (qID >= 0)
                            {
                                matA.At(id, qID, -1);
                            }
                        }

                        // Matrix B

                        double Bi = 0;
                        foreach (Point newQ in Np)
                        {
                            // Check Point Id of Old Q
                            int qID = pointId[newQ.X - tarTopLeftX, newQ.Y - tarTopLeftY];
                            // Q is on the boundry
                            if (qID == -1)
                            {
                                Bi += resultImg.Data[newQ.X, newQ.Y, k];
                            }

                            Point oldQ = new Point(newQ.X - tarTopLeftX, newQ.Y - tarTopLeftY);
                            Bi += zoomSrcImg.Data[oldP.X, oldP.Y, k] - zoomSrcImg.Data[oldQ.X, oldQ.Y, k];
                        }
                        matB.At(id, Bi);
                    }//);
                    Console.WriteLine("Generate Matrix Done. Time:" + DateTime.Now.Subtract(startTime).TotalSeconds);

                    // Solve the sparse linear equation using BiCgStab (Bi-Conjugate Gradient Stabilized)
                    var fp = LA.Double.Vector.Build.Dense(contentNum);
                    BiCgStab solver = new BiCgStab();

                    // Choose stop criterias
                    // Learn about stop criteria from: wo80, http://mathnetnumerics.codeplex.com/discussions/404689
                    var stopCriterias = new List<IIterationStopCriterion<double>>()
                    {
                        new ResidualStopCriterion<double>(1e-5),
                        new IterationCountStopCriterion<double>(1000),
                        new DivergenceStopCriterion<double>(),
                        new FailureStopCriterion<double>()
                    };

                    solver.Solve(matA, matB, fp, new Iterator<double>(stopCriterias), new DiagonalPreconditioner());
                    Console.WriteLine("Equation Solved. Time:" + DateTime.Now.Subtract(startTime).TotalSeconds);
                    // Console.WriteLine(fp);

                    // Set the color
                    for (var id = 0; id < contentNum; ++id)
                    {
                        int color = (int)fp.At(id);
                        if (color < 0)
                            color = 0;
                        if (color > 255)
                            color = 255;
                        //contentColor[k, id] = color;
                        resultImg.Data[contentList[id].X + tarTopLeftX, contentList[id].Y + tarTopLeftY, k] = (Byte)color;
                    }
                });

                //Paint
                //for (var id = 0; id < contentNum; ++id)
                //{
                //    resultImg[contentList[id].X + tarTopLeftX, contentList[id].Y + tarTopLeftY] = new Bgr(
                //        contentColor[0, id], contentColor[1, id], contentColor[2, id]);
                //}
                imgModifiedList[currImgIdFusion] = resultImg.Copy();
                pictureBoxImgFusion.Image = resultImg.ToBitmap();
                Console.WriteLine("Painting Finished. Time:" + DateTime.Now.Subtract(startTime).TotalSeconds);
            }
        }
コード例 #48
0
        public void CanSolveForRandomVector(int order)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
            var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

            var monitor = new Iterator<Complex>(
                new IterationCountStopCriterium<Complex>(1000),
                new ResidualStopCriterium(1e-10));

            var solver = new BiCgStab();

            var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
            Assert.AreEqual(matrixA.ColumnCount, resultx.Count);

            var matrixBReconstruct = matrixA*resultx;

            // Check the reconstruction.
            for (var i = 0; i < order; i++)
            {
                Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-5);
                Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-5);
            }
        }
コード例 #49
0
        public void SolveWideMatrix()
        {
            var matrix = new SparseMatrix(2, 3);
            Vector<Complex32> input = new DenseVector(2);

            var solver = new BiCgStab();
            solver.Solve(matrix, input);
        }
コード例 #50
0
        public void SolveLongMatrix()
        {
            var matrix = new SparseMatrix(3, 2);
            Vector<Complex> input = new DenseVector(3);

            var solver = new BiCgStab();
            solver.Solve(matrix, input);
        }
コード例 #51
0
        public void CanSolveForRandomVector(int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
                var vectorb = Vector<Complex32>.Build.Random(order, 1);

                var monitor = new Iterator<Complex32>(
                    new IterationCountStopCriterium<Complex32>(1000),
                    new ResidualStopCriterium<Complex32>(Math.Pow(1.0 / 10.0, iteration)));

                var solver = new BiCgStab();

                var resultx = matrixA.SolveIterative(vectorb, solver, monitor);

                if (monitor.Status != IterationStatus.Converged)
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA*resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float) Math.Pow(1.0/10.0, iteration - 3));
                    Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float) Math.Pow(1.0/10.0, iteration - 3));
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }
コード例 #52
0
        public void SolvePoissonMatrixAndBackMultiply()
        {
            // Create the matrix
            var matrix = new SparseMatrix(25);

            // Assemble the matrix. We assume we're solving the Poisson equation
            // on a rectangular 5 x 5 grid
            const int GridSize = 5;

            // The pattern is:
            // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
            for (var i = 0; i < matrix.RowCount; i++)
            {
                // Insert the first set of -1's
                if (i > (GridSize - 1))
                {
                    matrix[i, i - GridSize] = -1;
                }

                // Insert the second set of -1's
                if (i > 0)
                {
                    matrix[i, i - 1] = -1;
                }

                // Insert the centerline values
                matrix[i, i] = 4;

                // Insert the first trailing set of -1's
                if (i < matrix.RowCount - 1)
                {
                    matrix[i, i + 1] = -1;
                }

                // Insert the second trailing set of -1's
                if (i < matrix.RowCount - GridSize)
                {
                    matrix[i, i + GridSize] = -1;
                }
            }

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, i => 1);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator(new IIterationStopCriterium <float>[]
            {
                new IterationCountStopCriterium <float>(MaximumIterations),
                new ResidualStopCriterium(ConvergenceBoundary),
                new DivergenceStopCriterium(),
                new FailureStopCriterium()
            });
            var solver = new BiCgStab(monitor);

            // Solve equation Ax = y
            var x = solver.Solve(matrix, y);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status is CalculationConverged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.IsTrue(Math.Abs(y[i] - z[i]).IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
            }
        }
コード例 #53
0
        public void SolvePoissonMatrixAndBackMultiply()
        {
            // Create the matrix
            var matrix = new SparseMatrix(25);

            // Assemble the matrix. We assume we're solving the Poisson equation
            // on a rectangular 5 x 5 grid
            const int GridSize = 5;

            // The pattern is:
            // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
            for (var i = 0; i < matrix.RowCount; i++)
            {
                // Insert the first set of -1's
                if (i > (GridSize - 1))
                {
                    matrix[i, i - GridSize] = -1;
                }

                // Insert the second set of -1's
                if (i > 0)
                {
                    matrix[i, i - 1] = -1;
                }

                // Insert the centerline values
                matrix[i, i] = 4;

                // Insert the first trailing set of -1's
                if (i < matrix.RowCount - 1)
                {
                    matrix[i, i + 1] = -1;
                }

                // Insert the second trailing set of -1's
                if (i < matrix.RowCount - GridSize)
                {
                    matrix[i, i + GridSize] = -1;
                }
            }

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, i => Complex32.One);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator<Complex32>(
                new IterationCountStopCriterium<Complex32>(MaximumIterations),
                new ResidualStopCriterium<Complex32>(ConvergenceBoundary),
                new DivergenceStopCriterium<Complex32>(),
                new FailureStopCriterium<Complex32>());

            var solver = new BiCgStab();

            // Solve equation Ax = y
            var x = matrix.SolveIterative(y, solver, monitor);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
            }
        }
コード例 #54
0
        public void SolvePoissonMatrixAndBackMultiply()
        {
            // Create the matrix
            var matrix = new SparseMatrix(100);

            // Assemble the matrix. We assume we're solving the Poisson equation
            // on a rectangular 10 x 10 grid
            const int GridSize = 10;

            // The pattern is:
            // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
            for (var i = 0; i < matrix.RowCount; i++)
            {
                // Insert the first set of -1's
                if (i > (GridSize - 1))
                {
                    matrix[i, i - GridSize] = -1;
                }

                // Insert the second set of -1's
                if (i > 0)
                {
                    matrix[i, i - 1] = -1;
                }

                // Insert the centerline values
                matrix[i, i] = 4;

                // Insert the first trailing set of -1's
                if (i < matrix.RowCount - 1)
                {
                    matrix[i, i + 1] = -1;
                }

                // Insert the second trailing set of -1's
                if (i < matrix.RowCount - GridSize)
                {
                    matrix[i, i + GridSize] = -1;
                }
            }

            // Create the y vector
            Vector y = DenseVector.Create(matrix.RowCount, i => 1);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator(new IIterationStopCriterium[]
                {
                    new IterationCountStopCriterium(MaximumIterations),
                    new ResidualStopCriterium(ConvergenceBoundary),
                    new DivergenceStopCriterium(),
                    new FailureStopCriterium()
                });
            var solver = new BiCgStab(monitor);

            // Solve equation Ax = y
            var x = solver.Solve(matrix, y);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status is CalculationConverged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
#if !PORTABLE
                Assert.IsTrue(Math.Abs(y[i] - z[i]).IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
#else
                Assert.IsTrue(Math.Abs(y[i] - z[i]).IsSmaller(ConvergenceBoundary * 100.0, 1), "#05-" + i);
#endif
            }
        }
コード例 #55
0
        public void SolveUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            var matrix = SparseMatrix.CreateIdentity(100);

            // Create the y vector
            var y = DenseVector.Create(matrix.RowCount, i => Complex32.One);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator<Complex32>(
                new IterationCountStopCriterium<Complex32>(MaximumIterations),
                new ResidualStopCriterium<Complex32>(ConvergenceBoundary),
                new DivergenceStopCriterium<Complex32>(),
                new FailureStopCriterium<Complex32>());

            var solver = new BiCgStab();

            // Solve equation Ax = y
            var x = matrix.SolveIterative(y, solver, monitor);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
            }
        }
コード例 #56
0
        public void SolveUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            Matrix matrix = SparseMatrix.Identity(100);

            // Create the y vector
            Vector y = DenseVector.Create(matrix.RowCount, i => 1);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator(new IIterationStopCriterium[]
                {
                    new IterationCountStopCriterium(MaximumIterations),
                    new ResidualStopCriterium(ConvergenceBoundary),
                    new DivergenceStopCriterium(),
                    new FailureStopCriterium()
                });
            var solver = new BiCgStab(monitor);

            // Solve equation Ax = y
            var x = solver.Solve(matrix, y);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status is CalculationConverged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.IsTrue((y[i] - z[i]).IsSmaller(ConvergenceBoundary, 1), "#05-" + i);
            }
        }
コード例 #57
0
        public void SolveScaledUnitMatrixAndBackMultiply()
        {
            // Create the identity matrix
            var matrix = Matrix<double>.Build.SparseIdentity(100);

            // Scale it with a funny number
            matrix.Multiply(Math.PI, matrix);

            // Create the y vector
            var y = Vector<double>.Build.Dense(matrix.RowCount, 1);

            // Create an iteration monitor which will keep track of iterative convergence
            var monitor = new Iterator<double>(
                new IterationCountStopCriterium<double>(MaximumIterations),
                new ResidualStopCriterium<double>(ConvergenceBoundary),
                new DivergenceStopCriterium<double>(),
                new FailureStopCriterium<double>());

            var solver = new BiCgStab();

            // Solve equation Ax = y
            var x = matrix.SolveIterative(y, solver, monitor);

            // Now compare the results
            Assert.IsNotNull(x, "#02");
            Assert.AreEqual(y.Count, x.Count, "#03");

            // Back multiply the vector
            var z = matrix.Multiply(x);

            // Check that the solution converged
            Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");

            // Now compare the vectors
            for (var i = 0; i < y.Count; i++)
            {
                Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
            }
        }