Example #1
0
        /// <summary>
        /// Перемножает матрицы.
        /// </summary>
        /// <param name="A">Первый множитель</param>
        /// <param name="B">Второй множитель</param>
        /// <returns></returns>
        public static BaseMatrix Multiplication(BaseMatrix A, BaseMatrix B)
        {
            if ((A.Matrix.Count == 0) || (B.Matrix.Count == 0) || (A == null) || (B == null))
            {
                throw new NullReferenceException("You tried multiplicate empty matrix!");
            }
            if (B.Matrix[0].Length != A.Matrix.Count)
            {
                throw new ArgumentException("Matrices are incompatible for multiplication!");
            }

            BaseMatrix C = new BaseMatrix();

            for (int i = 0; i < A.Matrix[0].Length; i++)
            {
                int[] helper = new int[B.Matrix.Count];

                for (int j = 0; j < B.Matrix.Count; j++)
                {
                    for (int k = 0; k < A.Matrix.Count; k++)
                    {
                        helper[j] += A.Matrix[k][i] * B.Matrix[j][k];
                    }
                    helper[j] %= 2;
                }
                C.Matrix.Add(helper);
            }

            return(C);
        }
Example #2
0
        public void BaseMatrix_SumMatrix()
        {
            int[][] m = new int[][]
            {
                new int[] { 1, 0, 4 },
                new int[] { 0, 1, 0 },
                new int[] { 4, 0, 1 },
            };

            BaseMatrix <int> matrix1 = BaseMatrix <int> .CreateMatrix(m);

            int[][] m2 = new int[][]
            {
                new int[] { 1, 0, 2 },
                new int[] { 3, 1, 3 },
                new int[] { 2, 0, 1 }
            };
            BaseMatrix <int> matrix2 = BaseMatrix <int> .CreateMatrix(m2);

            BaseMatrix <int> matrix3 = matrix1 + matrix2;

            int[][] m3 = new int[][]
            {
                new int[] { 2, 0, 6 },
                new int[] { 3, 2, 3 },
                new int[] { 6, 0, 2 },
            };

            BaseMatrix <int> expected = BaseMatrix <int> .CreateMatrix(m3);

            Assert.IsFalse(!BaseMatrix <int> .MatrixComparer(matrix3, expected));
        }
Example #3
0
 // reset a shape in use
 public void Reset()
 {
     // reset position to base and change state
     ScreenPosition          = BaseScreenPosition;
     CurrentMatrixDimensions = BaseMatrixDimensions;
     ShapeOrigin             = new Vector2(CurrentMatrixDimensions.X * TileSize.X / 2,
                                           CurrentMatrixDimensions.Y * TileSize.Y / 2);
     CurrentMatrix          = BaseMatrix.Clone() as int[][];
     currentRotationIdx     = 0;
     cursorReturnOffset     = Vector2.Zero;
     destinationRotationIdx = 0;
     isFlippedHorizontal    = false;
     isFlippedVertical      = false;
     isFlippingHorizontal   = false;
     isFlippingVertical     = false;
     isFlipMidway           = false;
     isRotatingCW           = false;
     isRotatingCCW          = false;
     isValid           = false;
     isSnapped         = false;
     rotation          = 0f;
     scale             = Vector2.One;
     State             = ShapeState.Waiting;
     alpha             = 0f;
     timeIdle          = 0f;
     isDrawHighlighted = false;
 }
Example #4
0
        /// <summary>
        /// Extansion method for summ two matrix with element type T
        /// </summary>
        /// <typeparam name="T">type elements in matrix</typeparam>
        /// <param name="first">first matrix</param>
        /// <param name="second">second matrix</param>
        /// <returns>result matrix with element type T</returns>
        public static BaseMatrix <T> Add <T>(this BaseMatrix <T> first, BaseMatrix <T> second)
        {
            if (first == null)
            {
                throw new ArgumentNullException($"Argument {nameof(first)} is null");
            }

            if (second == null)
            {
                throw new ArgumentNullException($"Argument {nameof(second)} is null");
            }

            if (first.Size != second.Size)
            {
                throw new InvalidOperationException($"Size matrixs for add are not the same");
            }

            BaseMatrix <T> result;

            try
            {
                result = Add((dynamic)first, (dynamic)second);
            }
            catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
            {
                throw new NotSupportedException($"Type {nameof(T)} doesn`t support addition operation");
            }

            return(result);
        }
Example #5
0
        public static void OutputGenericMatrix(string fileName, BaseMatrix matrix)
        {
            Logger log = Logger.Instance;

            try
            {
                using (StreamWriter streamWriter = new StreamWriter(fileName))
                {
                    log.Info("Вывод матрицы в файл в обобщенном формате" + fileName + "...");

                    int n = 0;
                    matrix.Run((i, j, u) => { if (u != 0)
                                              {
                                                  n++;
                                              }
                               });
                    streamWriter.WriteLine(n);
                    matrix.Run((i, j, u) => { if (u != 0)
                                              {
                                                  streamWriter.WriteLine(String.Format("{0} {1} {2}", i, j, u));
                                              }
                               });
                    log.Info("Вывод матрицы в файл завершен.");
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                log.Error("Аварийное завершение вывода матрицы.");
            }
        }
Example #6
0
        /// <summary>
        /// Создает код на основе полученной матрицы, устонавливая его основные параметры.
        /// </summary>
        /// <param name="generatingMatrix">Порождающая матрица</param>
        /// <param name="line">Система уравнений, порождающая код</param>
        public Code(SolutionsMatrix generatingMatrix, string[] line)
        {
            if (generatingMatrix.Matrix.Count < generatingMatrix.Matrix[0].Length)
            {
                throw new CodeGeneratingException("Система имеет недостаточно решений для генерации кода.");
            }

            this.generatingMatrix = generatingMatrix;
            systemOfEquations     = line;
            allCodeWords          = new BaseMatrix();
            for (int possibleCodeNumber = 0; possibleCodeNumber < Math.Pow(2, K); possibleCodeNumber++)
            {
                int[]      intArrayPossibleCodeNumber = MyStatics.ToBinaryIntArray(possibleCodeNumber, K);
                BaseMatrix vectorPossibleCodeNumber   = new BaseMatrix();
                for (int i = 0; i < K; i++)
                {
                    int[] nextLine = { intArrayPossibleCodeNumber[i] };
                    vectorPossibleCodeNumber.Matrix.Add(nextLine);
                }
                BaseMatrix vectorPossibleCode = MyStatics.Multiplication(vectorPossibleCodeNumber, generatingMatrix);
                allCodeWords.Matrix.Add(vectorPossibleCode.Matrix[0]);
            }

            this.t = (MyStatics.FindMinDistance(AllCodeWords) - 1) / 2;
        }
Example #7
0
        /// <summary>
        /// Кодирует полученное сообщение.
        /// </summary>
        /// <param name="ourMessage">Кодируемое слово</param>
        /// <returns>Код</returns>
        public int[] Encode(int[] ourMessage)
        {
            BaseMatrix A = new BaseMatrix(ourMessage);
            BaseMatrix C = MyStatics.Multiplication(A, generatingMatrix);;

            return(C.Matrix[0]);
        }
Example #8
0
 public static EmptyPreconditioner Create(BaseMatrix source)
 {
     return(new EmptyPreconditioner()
     {
         sourceMatrix = source
     });
 }
Example #9
0
 public static LUsqPreconditioner Create(BaseMatrix source)
 {
     return(new LUsqPreconditioner()
     {
         sourceMatrix = source,
         LUsqMatrix = source.LUsq()
     });
 }
Example #10
0
        public void Constructor_Normal_Works(int rows, int columns)
        {
            var matrix = new BaseMatrix <int>(rows, columns);

            Assert.Equal(matrix.Rows, rows);

            Assert.Equal(matrix.Columns, columns);
        }
Example #11
0
 public static LLTPreconditioner Create(BaseMatrix source)
 {
     return(new LLTPreconditioner()
     {
         sourceMatrix = source,
         LLTmatrix = source.LLt()
     });
 }
Example #12
0
 static public DiagonalPreconditioner Create(BaseMatrix matrix)
 {
     return(new DiagonalPreconditioner()
     {
         sourceMatrix = matrix,
         diagsqrt = Sqrt(matrix)
     });
 }
Example #13
0
        public void Constructor_Normal_FillsDefault()
        {
            // it should be expected that when we create a new matrix all the values are defaulted to not-null
            var matrix = new BaseMatrix <int>(10, 10);

            foreach (var row in matrix)
            {
                foreach (var element in row)
                {
                    Assert.Equal(default, element);
Example #14
0
        public void BaseMatrix_SymmetricMatrix()
        {
            int[][] m = new int[][]
            {
                new int[] { 1, 0, 2 },
                new int[] { 0, 1, 0 },
                new int[] { 2, 0, 1 },
            };

            BaseMatrix <int> matrix1 = BaseMatrix <int> .CreateMatrix(m);

            Assert.AreEqual(typeof(SymmetricMatrix <int>), matrix1.GetType());
        }
Example #15
0
        public void BaseMatrix_DiagonalMatrix()
        {
            int[][] m = new int[][]
            {
                new int[] { 1, 0, 0 },
                new int[] { 0, 1, 0 },
                new int[] { 0, 0, 1 },
            };

            BaseMatrix <int> matrix1 = BaseMatrix <int> .CreateMatrix(m);

            Assert.AreEqual(typeof(DiagonalMatrix <int>), matrix1.GetType());
        }
Example #16
0
        public void BaseMatrix_SimpleMatrix()
        {
            int[][] m = new int[][]
            {
                new int[] { 1, 0, 2 },
                new int[] { 1, 1, 0 },
                new int[] { 2, 0, 1 },
                new int[] { 14, 3, 2 }
            };

            BaseMatrix <int> matrix1 = BaseMatrix <int> .CreateMatrix(m);

            Assert.AreEqual(typeof(BaseMatrix <int>), matrix1.GetType());
        }
Example #17
0
        private static Vector Sqrt(BaseMatrix matrix)
        {
            var vec = matrix.Diagonal.Clone() as Vector;

            for (int i = 0; i < vec.Size; i++)
            {
                vec[i] = Math.Sqrt(vec[i]);
                if (!(vec[i] == vec[i]))
                {
                    throw new Exception(String.Concat("Предобусловливание Diagonal : извлечение корня из отричательного числа, элемент диагонали №", i));
                }
            }
            return(vec);
        }
        public void DiagonalMatrixTest()
        {
            DiagonalMatrix <int> dm1 = new DiagonalMatrix <int>(3, 6, 2, 1);
            DiagonalMatrix <int> dm2 = new DiagonalMatrix <int>(3, 6, 2, 1);
            BaseMatrix <int>     dm3 = dm1.Add(dm2);

            int[,] matrix = dm3.Matrix;
            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
Example #19
0
        private void Validate(BaseMatrix <T> lhs, BaseMatrix <T> rhs)
        {
            if (lhs == null)
            {
                throw new ArgumentNullException($"{nameof(lhs)} cannot be null");
            }

            if (rhs == null)
            {
                throw new ArgumentNullException($"{nameof(lhs)} cannot be null");
            }

            if (lhs.Size != rhs.Size)
            {
                throw new ArgumentException("Sizes of matrixes have to be equal!");
            }
        }
Example #20
0
        public object Clone()
        {
            Shape shape = new Shape();

            shape.alpha = alpha;
//            shape.AssetName = AssetName;
            shape.BaseMatrix              = (baseMatrix != null ? BaseMatrix.Clone() as int[][] : null);
            shape.BaseMatrixDimensions    = BaseMatrixDimensions;
            shape.BaseOrigin              = BaseOrigin;
            shape.BaseScreenPosition      = BaseScreenPosition;
            shape.CurrentMatrix           = (currentMatrix != null ? CurrentMatrix.Clone() as int[][] : null);
            shape.CurrentMatrixDimensions = CurrentMatrixDimensions;
            shape.currentRotationIdx      = currentRotationIdx;
            shape.CursorReturnOffset      = CursorReturnOffset;
            shape.destinationRotationIdx  = destinationRotationIdx;
            shape.IsDrawHighlighted       = IsDrawHighlighted;
            shape.horizontalFlipScale     = horizontalFlipScale;
            shape.isFlipMidway            = isFlipMidway;
            shape.isFlippedHorizontal     = isFlippedHorizontal;
            shape.isFlippedVertical       = isFlippedVertical;
            shape.isFlippingHorizontal    = isFlippingHorizontal;
            shape.isFlippingVertical      = isFlippingVertical;
            shape.isRotatingCW            = isRotatingCW;
            shape.isRotatingCCW           = isRotatingCCW;
            shape.IsSnapCueOnFlipFinish   = IsSnapCueOnFlipFinish;
            shape.IsSnapCueOnRotateFinish = IsSnapCueOnRotateFinish;
            shape.IsValid            = IsValid;
            shape.Key                = Key;
            shape.MusicCueName       = MusicCueName;
            shape.Name               = Name;
            shape.rotation           = rotation;
            shape.scale              = scale;
            shape.ShapeOrigin        = ShapeOrigin;
            shape.ScreenPosition     = ScreenPosition;
            shape.shapeResetDistance = shapeResetDistance;
            shape.State              = State;
            shape.texture            = Texture;
            shape.textureHL          = TextureHL;
            shape.TextureContentName = TextureContentName;
            shape.TileSize           = TileSize;
            shape.TimeIdle           = TimeIdle;
            shape.transition         = transition;
            shape.verticalFlipScale  = verticalFlipScale;

            return(shape);
        }
Example #21
0
        private bool IsEqual(BaseMatrix <int> matrix, int[] expectedResult)
        {
            int count = 0;

            for (int i = 0; i < matrix.Size; i++)
            {
                for (int j = 0; j < matrix.Size; j++)
                {
                    if (!(matrix[i, j].Equals(expectedResult[count++])))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        public void DiagonalMatrixSum()
        {
            SquareMatrix <int>   square   = new SquareMatrix <int>(4, array);
            DiagonalMatrix <int> diagonal = new DiagonalMatrix <int>(4);
            BaseMatrix <int>     actual   = square.Sum(diagonal, new Add());
            BaseMatrix <int>     expected = new SquareMatrix <int>(4, new int[, ] {
                { 4, 5, 6, 7 }, { 5, 4, 3, 2 },
                { 7, 8, 8, 9 }, { 6, 1, 24, 5 }
            });

            for (int i = 0; i < Math.Sqrt(actual.Length); i++)
            {
                for (int j = 0; j < Math.Sqrt(actual.Length); j++)
                {
                    Assert.AreEqual(expected[i, j], actual[i, j]);
                }
            }
        }
        public void SquareMatrixSum()
        {
            SquareMatrix <int> square1  = new SquareMatrix <int>(4, array);
            SquareMatrix <int> square2  = new SquareMatrix <int>(4, array);
            BaseMatrix <int>   actual   = square1.Sum(square2, new Add());
            BaseMatrix <int>   expected = new SquareMatrix <int>(4, new int[, ] {
                { 8, 10, 12, 14 }, { 10, 8, 6, 4 },
                { 14, 16, 16, 18 }, { 12, 2, 48, 10 }
            });

            for (int i = 0; i < Math.Sqrt(actual.Length); i++)
            {
                for (int j = 0; j < Math.Sqrt(actual.Length); j++)
                {
                    Assert.AreEqual(expected[i, j], actual[i, j]);
                }
            }
        }
        public void SquareMatrixTest()
        {
            int[] elems = new int[] { 1, 2, 3 };
            SymmetricMatrix <int> sm1 = new SymmetricMatrix <int>(elems, 4, 5, 6);

            SymmetricMatrix <int> sm2 = new SymmetricMatrix <int>(elems, 7, 8, 9);
            BaseMatrix <int>      sm3 = sm1.Add(sm2);

            int[,] matrix = sm3.Matrix;
            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
        public bool IsEqual(BaseMatrix <T> first, BaseMatrix <T> second)
        {
            var sizeMin = first.Size <= second.Size ? first.Size : second.Size;

            var equalityComparer = EqualityComparer <T> .Default;

            for (int i = 0; i < sizeMin; i++)
            {
                for (int j = 0; j < sizeMin; j++)
                {
                    if (!equalityComparer.Equals(first[i, j], second[i, j]))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #26
0
        /// <summary>
        /// Ищет минимальное расстояние в коде.
        /// </summary>
        /// <param name="allCodeWords">Множество всех кодовых слов</param>
        /// <returns>Минимальное расстояние</returns>
        public static int FindMinDistance(BaseMatrix allCodeWords)
        {
            int minDistance = Int32.MaxValue, currentDistance = 0;

            for (int i = 0; i < allCodeWords.Matrix.Count; i++)
            {
                for (int j = i + 1; j < allCodeWords.Matrix.Count; j++)
                {
                    for (int k = 0; k < allCodeWords.Matrix[0].Length; k++)
                    {
                        currentDistance += (allCodeWords.Matrix[i][k] + allCodeWords.Matrix[j][k]) % 2;
                    }
                    if (currentDistance < minDistance)
                    {
                        minDistance = currentDistance;
                    }
                    currentDistance = 0;
                }
            }
            return(minDistance);
        }
        public void SymmetricalMatrixSum()
        {
            SquareMatrix <int>      square      = new SquareMatrix <int>(4, array);
            SymmetricalMatrix <int> symmetrical = new SymmetricalMatrix <int>(4, new int[, ] {
                { 1, 2, 3, 4 }, { 2, 0, 0, 0 },
                { 3, 0, 0, 0 }, { 4, 0, 0, 0 }
            });
            BaseMatrix <int> actual   = square.Sum(symmetrical, new Add());
            BaseMatrix <int> expected = new SquareMatrix <int>(4, new int[, ] {
                { 5, 7, 9, 11 }, { 7, 4, 3, 2 },
                { 10, 8, 8, 9 }, { 10, 1, 24, 5 }
            });

            for (int i = 0; i < Math.Sqrt(actual.Length); i++)
            {
                for (int j = 0; j < Math.Sqrt(actual.Length); j++)
                {
                    Assert.AreEqual(expected[i, j], actual[i, j]);
                }
            }
        }
Example #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MatrixVisitor{T}"/> class.
 /// </summary>
 /// <param name="other">The other.</param>
 public MatrixVisitor(BaseMatrix <T> other)
 {
     temp = other;
 }
Example #29
0
        public static BaseMatrix <T> Add <T>(this BaseMatrix <T> m1, BaseMatrix <T> m2)
        {
            var visitor = new SumVisitor <T>();

            return(visitor.DymanicVisit(m1, m2));
        }
Example #30
0
 /// <summary>
 /// In place matrix subtraction, A=A-B
 /// </summary>
 /// <param name="B">The Matrix</param>
 public void SubtractInplace(BaseMatrix B)
 {
     CheckMatrixDimensions(B);
     double[] BData = B.Data;
     for (int i = 0; i < this._Data.Length; i++)
     {
         this._Data[i] -= BData[i];
     }
 }
Example #31
0
 public BaseMatrix <T> DymanicVisit(BaseMatrix <T> lhs, BaseMatrix <T> rhs)
 {
     return(Visit((dynamic)lhs, (dynamic)rhs));
 }
Example #32
0
        /// <summary>
        /// Sets the matrix to show.
        /// </summary>
        /// <param name="matrix">A real matrix.</param>
        public void Matrix(BaseMatrix matrix)
        {
            this._RealMatrix = matrix;
            this._IsRealMatrix = true;

            this._ComplexMatrix = new ComplexMatrix(1);

            this.ShowMatrix();
        }
Example #33
0
        /// <summary>
        /// Sets the matrix to show.
        /// </summary>
        /// <param name="matrix">A complex matrix.</param>
        public void Matrix(ComplexMatrix matrix)
        {
            this._ComplexMatrix = matrix;
            this._IsRealMatrix = false;

            this._RealMatrix = new Matrix(1);

            this.ShowMatrix();
        }
Example #34
0
 public MatrixDebuggerDisplay(BaseMatrix matrix)
 {
     this.MeMatrix = matrix;
 }
Example #35
0
        private void CheckDimensions(BaseMatrix matrixA, BaseMatrix matrixB)
        {
            if (matrixA.IsSquare!= true)
            {
                throw new System.ArgumentException("Matrix A is not a square matrix.");
            }

            if (matrixA.RowCount != matrixB.RowCount)
            {
                throw new System.ArgumentException("Matrix dimensions are not valid.");
            }
        }
Example #36
0
        /// <summary>
        /// In place addition A=A+B
        /// </summary>
        /// <param name="B">The Matrix</param>
        public void AddInplace(BaseMatrix B)
        {
            base.CheckMatrixDimensions(B);

            double[] BData = B.Data;
            for (int i = 0; i < this._Data.Length; i++)
            {
                this._Data[i] += BData[i];
            }
        }
Example #37
0
 private void CheckDimensions(BaseMatrix matrixA)
 {
     if (matrixA.IsSquare != true)
     {
         throw new System.ArgumentException("Matrix A is not a square matrix.");
     }
 }
Example #38
0
        private void CheckDimensions(BaseMatrix matrixA, Vector vectorB)
        {
            if (matrixA.IsSquare != true)
            {
                throw new System.ArgumentException("Matrix A is not a square matrix.");
            }

            if (vectorB.Type != VectorType.Column)
            {
                throw new System.ArgumentException("The vector should be a column vector.");
            }

            if (matrixA.RowCount != vectorB.Length)
            {
                throw new System.ArgumentException("Matrix dimensions are not valid.");
            }
        }