Ejemplo n.º 1
0
 private void SortTableByKeyword(int keywordIndex)
 {
     matrix = matrixSorter.Sort(matrix, GetKeyword(keywordIndex));
 }
Ejemplo n.º 2
0
        static void Test()
        {
            Console.WriteLine("Запускаем Test() ...");
            Console.WriteLine();
            // Checking equation solution methods here
            double[] matrixValues = new double[]
            {
                -5, 14, -17,    // C0
                80, 24, -92,    // B0
                -32, -40, 94,   // A1
                -87, 42, 91,    // C1
                -13, -68, 12,   // B1
                -72, -89, -44,  // A2
                62, -66, -45    // C2
            };

            double[] rightSide = new double[]
            {
                51, -27, -59, 14, 70, 86, -7, -86, -12
            };

            BlockMatrix mat = new BlockMatrix(3, 3, matrixValues);

            Console.WriteLine("Решаем уравнение с матрицей:");
            Console.WriteLine();
            Console.WriteLine(mat);
            Console.WriteLine();
            Console.WriteLine("И правой частью:");
            Console.WriteLine();
            Console.WriteLine(rightSide.ToStringRow());
            Console.WriteLine();

            double[] csResult = new double[rightSide.Length];
            try
            {
                BlockMatrix.SolveSystem(mat, rightSide, csResult);
            }
            catch (ArithmeticException e)
            {
                Console.WriteLine("К сожалению, к данной матрице метод прогонки неприменим. Попробуйте взять матрицу с диагональным преобладанием.");
                Console.WriteLine();
                Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                Console.WriteLine();
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }

            Console.WriteLine("Код на C# выдал решение:");
            Console.WriteLine();
            Console.WriteLine(csResult.ToStringColumn());
            Console.WriteLine();

            Console.WriteLine("Которое при умножении на матрицу слева даёт:");
            Console.WriteLine();
            Console.WriteLine((mat * csResult).ToStringRow());
            Console.WriteLine();

            double[] cppResult = new double[rightSide.Length];
            double   time      = 0;

            SolveEquationCpp(mat.MatrixDimension, mat.BlockDimension, matrixValues, rightSide, cppResult, ref time);

            Console.WriteLine("Код на C++ выдал решение:");
            Console.WriteLine();
            Console.WriteLine(cppResult.ToStringColumn());
            Console.WriteLine();

            Console.WriteLine("Которое при умножении на матрицу слева даёт:");
            Console.WriteLine();
            Console.WriteLine((mat * cppResult).ToStringRow());
            Console.WriteLine();
        }
Ejemplo n.º 3
0
 private void BuildCharTable(int keywordIndex)
 {
     matrix = matrixBuilder.Build(GetKeywordLength(keywordIndex), this.cipherText.Length);
 }
Ejemplo n.º 4
0
Archivo: getrf.cs Proyecto: 0xCM/arrows
        /// <summary>
        /// Computes an LU factorization of an N-square matrix A using partial pivoting with row interchanges.
        /// </summary>
        /// <param name="A"></param>
        /// <param name="X"></param>
        /// <param name="P"></param>
        /// <typeparam name="M"></typeparam>
        /// <typeparam name="N"></typeparam>
        public static ref BlockMatrix <N, double> getrf <N>(BlockMatrix <N, double> A, Span <int> P, ref BlockMatrix <N, double> X)
            where N : ITypeNat, new()
        {
            var n   = nati <N>();
            var lda = n;

            A.CopyTo(ref X);
            var exit = LAPACK.LAPACKE_dgetrf(RowMajor, n, n, ref head(X), lda, ref head(P));

            checkx(exit);

            return(ref X);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Test();
            Console.WriteLine();

            TestTime log = new TestTime();

            if (TestTime.Load(logFilename, ref log) == false)
            {
                Console.WriteLine("Не получилось загрузить лог; будет создан пустой лог.");
                Console.WriteLine();
            }

            Console.WriteLine("Данная программа сравнивает время решения линейных уравнений с блочной трёхдиагональной матрицей в коде на C# и на C++.");
            Console.WriteLine();

            bool continueTests = true;

            while (continueTests)
            {
                Console.WriteLine("Провести тест? Введите 'y' для продолжения, 'n' для выхода из программы");
                string userInput = Console.ReadLine();
                Console.WriteLine();

                if (userInput == "n")
                {
                    continueTests = false;
                }
                else if (userInput != "y")
                {
                    Console.WriteLine("Команда введена с ошибками; возврат в главное меню.");
                    Console.WriteLine();
                    continue;
                }
                else
                {
                    int matDim, bloDim;  // Dimensions

                    Console.WriteLine("Введите блочный порядок матрицы (количество блоков вдоль каждой из сторон матрицы):");
                    try  // Getting matrix dimension
                    {
                        matDim = int.Parse(Console.ReadLine());
                        if (matDim < 2)
                        {
                            throw new ArgumentException("Порядок матрицы должен быть натуральным числом, не меньшим 2.");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Порядок блочной матрицы введён с ошибками");
                        Console.WriteLine();
                        Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                        Console.WriteLine();
                        continue;
                    }

                    Console.WriteLine("Введите порядок блока (количество чисел вдоль каждой из сторон блока):");
                    try  // Getting block dimension
                    {
                        bloDim = int.Parse(Console.ReadLine());
                        if (bloDim < 1)
                        {
                            throw new ArgumentException("Порядок блока должен быть натуральным числом, не меньшим 1.");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Порядок блока введён с ошибками");
                        Console.WriteLine();
                        Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                        Console.WriteLine();
                        continue;
                    }

                    // Preparations

                    double[] rightSide = null;
                    double   csTime = 0, cppTime = 0;
                    double[] csResult  = null;
                    double[] cppResult = null;

                    try  // Allocating memory
                    {
                        rightSide = new double[matDim * bloDim];
                        for (int i = 0; i < rightSide.Length; ++i)
                        {
                            rightSide[i] = 1;
                        }
                        csResult  = new double[rightSide.Length];
                        cppResult = new double[rightSide.Length];
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Не удалось выделить память под массивы правой части/решений. Вероятно, были указаны слишком большие размеры матрицы.");
                        Console.WriteLine();
                        Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                        Console.WriteLine();
                        continue;
                    }

                    BlockMatrix mat;
                    try  // C# solution
                    {
                        mat = new BlockMatrix(matDim, bloDim);
                        Stopwatch watch = new Stopwatch();

                        try
                        {
                            watch.Start();
                            BlockMatrix.SolveSystem(mat, rightSide, csResult);
                            watch.Stop();
                        }
                        catch (ArithmeticException e)
                        {
                            Console.WriteLine("К сожалению, к данной матрице метод прогонки неприменим. Попробуйте взять матрицу с диагональным преобладанием.");
                            Console.WriteLine();
                            Console.WriteLine($"Сообщение об ошибке: {e.Message}");
                            Console.WriteLine();
                            continue;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            continue;
                        }
                        finally
                        {
                            watch.Stop();
                        }

                        csTime = watch.ElapsedMilliseconds;
                        Console.WriteLine($"Решение на C# успешно завершилось за {csTime} миллисекунд.");
                        Console.WriteLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Something broke unexpectedly: {e.Message}");
                        if (e.InnerException != null)
                        {
                            Console.WriteLine(e.InnerException.Message);
                        }

                        continue;
                    }

                    try  // CPP solution
                    {
                        SolveEquationCpp(matDim, bloDim, mat.ToPlainArray(), rightSide, cppResult, ref cppTime);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Something broke unexpectedly: {e.Message}");
                        if (e.InnerException != null)
                        {
                            Console.WriteLine(e.InnerException.Message);
                        }

                        continue;
                    }

                    double ratio = (cppTime > 0) ? ((double)csTime) / cppTime : -1;

                    log.Add(TestTime.FormatString(matDim, bloDim, csTime, cppTime, ratio));
                }
            }

            if (TestTime.Save(logFilename, log) == false)
            {
                Console.WriteLine("Не получилось сохранить лог; результаты данного запуска программы не сохранены.");
            }

            Console.WriteLine("Завершаем работу программы. Содержимое журнала:");
            Console.WriteLine();

            Console.WriteLine(log);

            Console.WriteLine("Нажмите ENTER для завершения...");
            Console.ReadLine();
        }
Ejemplo n.º 6
0
 private void DecryptTextWithKeyword(Keyword keyword)
 {
     matrix = BuildBlockMatrix(keyword);
     FillBlockTable(keyword);
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Populates a target matrix with the product of the operands
 /// </summary>
 /// <param name="A">The left matrix</param>
 /// <param name="B">The right matrix</param>
 /// <param name="M">The number of rows in A and C</param>
 /// <param name="N">The number of columns in B and C</param>
 /// <param name="K">The number of columns in A and rows in B</param>
 public static ref BlockMatrix <N, T> gemm <N, T>(BlockMatrix <N, T> A, BlockMatrix <N, T> B, ref BlockMatrix <N, T> X)
     where N : ITypeNat, new()
     where T : struct
 {
     if (typeof(T) == typeof(float))
     {
         var Z = X.As <float>();
         gemm(A.As <float>(), B.As <float>(), ref Z);
     }
     else if (typeof(T) == typeof(double))
     {
         var x = X.As <double>();
         gemm(A.As <double>(), B.As <double>(), ref x);
     }
     else if (typeof(T) == typeof(int) || typeof(T) == typeof(uint) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort))
     {
         var Z = X.Convert <double>();
         X = gemm(A.Convert <double>(), B.Convert <double>(), ref Z).Convert <T>();
     }
     else if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong))
     {
         var Z = X.Convert <double>();
         X = gemm(A.Convert <double>(), B.Convert <double>(), ref Z).Convert <T>();
     }
     else if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
     {
         var Z = X.Convert <float>();
         X = gemm(A.Convert <float>(), B.Convert <float>(), ref Z).Convert <T>();
     }
     return(ref X);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Computes the product of square metrices X = AB
        /// </summary>
        /// <param name="A">The left matrix</param>
        /// <param name="B">The right matrix</param>
        /// <param name="X">The target matrix</param>
        /// <param name="N">The number of columns in B and C</param>
        public static ref BlockMatrix <N, double> gemm <N>(BlockMatrix <N, double> A, BlockMatrix <N, double> B, ref BlockMatrix <N, double> X)
            where N : ITypeNat, new()
        {
            var n  = nati <N>();
            var ld = n;

            CBLAS.cblas_dgemm(RowMajor, NoTranspose, NoTranspose, n, n, n, 1, ref head(A), ld, ref head(B), ld, 0, ref head(X), ld);
            return(ref X);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Populates a target matrix with the product of the operands
        /// </summary>
        /// <param name="A">The left matrix</param>
        /// <param name="B">The right matrix</param>
        /// <param name="M">The number of rows in A and C</param>
        /// <param name="N">The number of columns in B and C</param>
        /// <param name="K">The number of columns in A and rows in B</param>
        public static ref BlockMatrix <M, N, double> gemm <M, K, N>(BlockMatrix <M, K, double> A, BlockMatrix <K, N, double> B, ref BlockMatrix <M, N, double> X)
            where M : ITypeNat, new()
            where K : ITypeNat, new()
            where N : ITypeNat, new()
        {
            var m   = nati <M>();
            var k   = nati <K>();
            var n   = nati <N>();
            var lda = k;
            var ldb = n;
            var ldx = n;

            CBLAS.cblas_dgemm(RowMajor, NoTranspose, NoTranspose, m, n, k, 1d, ref head(A), lda, ref head(B), ldb, 0, ref head(X), ldx);
            return(ref X);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Allocates a target matrix and populates it with the product of the operands
        /// </summary>
        /// <param name="A">The left matrix</param>
        /// <param name="B">The right matrix</param>
        /// <param name="M">The number of rows in A and C</param>
        /// <param name="N">The number of columns in B and C</param>
        /// <param name="K">The number of columns in A and rows in B</param>
        public static BlockMatrix <M, N, float> gemm <M, K, N>(BlockMatrix <M, K, float> A, BlockMatrix <K, N, float> B)
            where M : ITypeNat, new()
            where K : ITypeNat, new()
            where N : ITypeNat, new()
        {
            var m   = nati <M>();
            var k   = nati <K>();
            var n   = nati <N>();
            var lda = k;
            var ldb = n;
            var ldx = n;
            var X   = BlockMatrix.Alloc <M, N, float>();

            CBLAS.cblas_sgemm(RowMajor, NoTranspose, NoTranspose, m, n, k, 1.0f, ref head(A), lda, ref head(B), ldb, 0, ref head(X), ldx);
            return(X);
        }