Example #1
0
File: ILU.cs Project: xyuan/BoSSS
        public void Solve <P, Q>(P X, Q B)
            where P : IList <double>
            where Q : IList <double>
        {
            int    n   = Mtx.NoOfCols;
            double sum = 0;

            var tempMtx = Mtx;

            // Zeros on diagonal elements because of saddle point structure
            for (int bla = 0; bla < n; bla++)
            {
                if (Mtx.GetDiagonalElement(bla) == 0)
                {
                    throw new Exception("One or more diagonal elements are zero, ILU cannot work");
                }
                Mtx.SetDiagonalElement(bla, 1);
            }


            // ILU decomposition of matrix
            for (int k = 0; k < n - 1; k++)
            {
                for (int i = k; i < n; i++)
                {
                    if (tempMtx[i, k] == 0)
                    {
                        i = n;
                    }
                    else
                    {
                        Mtx[i, k] = Mtx[i, k] / Mtx[k, k];
                        for (int j = k + 1; j < n; j++)
                        {
                            if (tempMtx[i, j] == 0)
                            {
                                j = n;
                            }
                            else
                            {
                                Mtx[i, j] = Mtx[i, j] - Mtx[i, k] * Mtx[k, j];
                            }
                        }
                    }
                }
            }


            // LU decomposition of matrix
            //for (int i = 0; i < n; i++) {
            //    for (int j = i; j < n; j++) {
            //        sum = 0;
            //        for (int k = 0; k < i; k++)
            //            sum += Mtx[i, k] * Mtx[k, j];
            //        Mtx[i, j] = tempMtx[i, j] - sum;
            //    }
            //    for (int j = i + 1; j < n; j++) {
            //        sum = 0;
            //        for (int k = 0; k < i; k++)
            //            sum += Mtx[j, k] * Mtx[k, i];
            //        Mtx[j, i] = (1 / Mtx[i, i]) * (tempMtx[j, i] - sum);
            //    }
            //}

            // find solution of Ly = b
            double[] y = new double[n];
            for (int i = 0; i < n; i++)
            {
                sum = 0;
                for (int k = 0; k < i; k++)
                {
                    sum += Mtx[i, k] * y[k];
                }
                y[i] = B[i] - sum;
            }
            // find solution of Ux = y
            for (int i = n - 1; i >= 0; i--)
            {
                sum = 0;
                for (int k = i + 1; k < n; k++)
                {
                    sum += Mtx[i, k] * X[k];
                }
                X[i] = (1 / Mtx[i, i]) * (y[i] - sum);
            }
        }