public void CompanionMatrixEigenvalues()
        {
            SquareMatrix CM = new SquareMatrix(3);
            CM[0, 2] = -1.0;
            CM[1, 0] = 1.0;
            CM[1, 2] = -3.0;
            CM[2, 1] = 1.0;
            CM[2, 2] = -3.0;
            ComplexEigensystem EM = CM.Eigensystem();
            for (int i = 0; i < EM.Dimension; i++) {
                Console.WriteLine("! {0}", EM.Eigenvalue(i));
            }

            for (int d = 2; d <= 8; d++) {

                Console.WriteLine(d);

                SquareMatrix C = new SquareMatrix(d);
                for (int r = 1; r < d; r++) {
                    C[r, r - 1] = 1.0;
                }
                for (int r = 0; r < d; r++) {
                    C[r, d - 1] = -AdvancedIntegerMath.BinomialCoefficient(d, r);
                }

                ComplexEigensystem e = C.Eigensystem();
                for (int i = 0; i < e.Dimension; i++) {
                    Console.WriteLine("!! {0}", e.Eigenvalue(i));
                }

            }
        }
        public void TestAddInt()
        {
            int[,] m = 
            {
                {1, 0, 2, 3},
                {2, 0, 3, 4},
                {3, 0, 4, 5},
                {4, 0, 5, 6}
            };
            int[] m2 = { 0, 3, 4, 4};

            SquareMatrix<int> matr1 = new SquareMatrix<int>(m);
            matr1.Add(new DiagonalMatrix<int>(m2));

            int[,] rezult = 
            {
                {1, 0, 2, 3},
                {2, 3, 3, 4},
                {3, 0, 8, 5},
                {4, 0, 5, 10}
            };
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    Assert.AreEqual(matr1[i, j], rezult[i, j]);
        }
        static void Main(string[] args)
        {
            SquareMatrix<int> squareMatrix = new SquareMatrix<int>(new int[2,2]);
            Informator informator = new Informator(squareMatrix);

            squareMatrix.ChangeElement(2, 3);
        }
        static void Main(string[] args)
        {
            int[,] first =
            {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
            };
            int[,] second =
            {
                {1, 2, 3},
                {2, 5, 6},
                {3, 6, 9}
            };
            int[,] third =
            {
                {1, 0, 0},
                {0, 5, 0},
                {0, 0, 9}
            };
            SquareMatrix<int> matrix = new SquareMatrix<int>(3);
            SquareMatrix<int> lol1 = new SquareMatrix<int>(first);
            SymmetricMatrix<int> lol2 = new SymmetricMatrix<int>(second);
            DiagonalMatrix<int> lol3 = new DiagonalMatrix<int>(third);
            matrix.MatrixChange += ShowChanges;
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    matrix[i, j] = i*j;

            var lol4 = lol3.Add(lol1);
            System.Console.ReadLine();
        }
        static MixedMatrixTest()
        {
            R = new RectangularMatrix(2, 3);
            R[0, 0] = 0;
            R[0, 1] = 1;
            R[0, 2] = 2;
            R[1, 0] = 3;
            R[1, 1] = 4;
            R[1, 2] = 5;

            M = new SquareMatrix(3);
            M[0, 0] = 0;
            M[0, 1] = 1;
            M[0, 2] = 2;
            M[1, 0] = 3;
            M[1, 1] = 4;
            M[1, 2] = 5;
            M[2, 0] = 6;
            M[2, 1] = 7;
            M[2, 2] = 8;

            S = new SymmetricMatrix(3);
            M[0, 0] = 0;
            M[0, 1] = 1;
            M[0, 2] = 2;
            M[1, 1] = 3;
            M[1, 2] = 4;
            M[2, 2] = 5;
        }
        public LUDecomposition(SquareMatrix incomingMatrix)
        {
            this.L = new SquareMatrix(incomingMatrix.Count);
            this.U = new SquareMatrix(incomingMatrix.Count);

            for (int counter = 0; counter < incomingMatrix.Count; counter++)
            {
                for (int counter1 = 0; counter1 < incomingMatrix.Count; counter1++)
                {
                    if (counter1 == counter)
                    {
                        this.L[counter][counter1] = 1;
                    }
                    if (counter1 >= counter)
                    {
                        this.U[counter][counter1] = incomingMatrix[counter][counter1] - this.sum(counter - 1, counter, counter1);

                        if (counter == counter1)
                        {
                            this.det *= this.U[counter][counter1];
                        }
                    }
                    else
                    {
                        this.L[counter][counter1] = (incomingMatrix[counter][counter1] - this.sum(counter1 - 1, counter, counter1)) / this.U[counter1][counter1];
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            int[,] matr1 = { { 1, 2, 3 }, 
                            { 1, 2, 3 }, 
                            { 1, 2, 3 } };
            SquareMatrix<int> matrix1 = new SquareMatrix<int>(matr1);

            int[,] matr2 = { { 1, 0, 0 }, 
                            { 0, 2, 0 }, 
                            { 0, 0, 3 } };
            DiagonalMatrix<int> matrix2 = new DiagonalMatrix<int>(matr2);

            int[,] matr3 = { { 1, 5, 3 }, 
                            { 5, 2, 7 }, 
                            { 3, 7, 3 } };
            SymmetricMatrix<int> matrix3 = new SymmetricMatrix<int>(matr3);

            var squar = new Listeners<int>();
            squar.Register(matrix1);
            squar.Register(matrix2);
            squar.Register(matrix3);

             matrix1[1, 2] = 3;
             matrix2[2, 2] = 3;
             matrix3[1, 0] = 3;


             SquareMatrix<int> output = matrix1.Sum(matrix2, (x, y) => x + y);
             SquareMatrix<int> output2 = matrix1.Sum(matrix2);
             Console.WriteLine();
            }
        static void Main(string[] args)
        {
            int[,] array = new int[2, 2] {{1, 2}, {3, 4}};
            Matrix<int> matrix = new SquareMatrix<int>(array);
            for (int i = 0; i < matrix.Order; i++)
            {
                for (int j = 0; j < matrix.Order; j++)
                {
                    Console.Write("{0, 4}", matrix[i, j]);
                }
                Console.WriteLine();
            }

            int[] arraySumRows = new int[] { 3, 7 };
            matrix.ElementChanged +=
                (sender, e) =>
                {
                    arraySumRows[e.i] -= e.OldValue;
                    arraySumRows[e.i] += e.NewValue;
                    Console.WriteLine("Element {0}, {1} changed from {2} to {3}", e.i, e.j, e.OldValue, e.NewValue);
                    Console.WriteLine("New sum row {0} = {1}", e.i, arraySumRows[e.i]);
                };
            for (int i = 0; i < matrix.Order; i++)
            {
                for (int j = 0; j < matrix.Order; j++)
                {
                    matrix[i, j]++;
                }
            }
        }
        static void Main(string[] args)
        {
            try
            {
                SquareMatrix<int> squareMatrix1 = new SquareMatrix<int>(new int[,] { { 1, 2 }, { 3, 4 } });
                SquareMatrix<int> squareMatrix2 = new SquareMatrix<int>(new int[,] { { 1, 2 }, { 3, 4 } });
                //SquareMatrix<int> squareMatrix2 = new SquareMatrix<int>(new int[,]{{1,2,3},{4,5,6}});
                SymmetricalMatrix<int> symmetricalMatrix1 = new SymmetricalMatrix<int>((new int[,] { { 1, 1 }, { 1, 4 } }));
                //SymmetricalMatrix<int> symmetricalMatrix2 = new SymmetricalMatrix<int>((new int[,] { { 1, 2 }, { 1, 4 } }));
                SquareMatrix<int> squareMatrix3 = new SymmetricalMatrix<int>((new int[,] { { 1, 1 }, { 1, 4 } }));
                SymmetricalMatrix<int> symmetricalMatrix3 = (SymmetricalMatrix<int>)squareMatrix3;
                DiagonalMatrix<int> diagonalMatrix1 = new DiagonalMatrix<int>(new int[,] { { 1, 0 }, { 0, 1 } });
                var client = new Client1<int>(squareMatrix1);
                var client2 = new Client1<int>(symmetricalMatrix1);
                squareMatrix1[0, 0] = 2;
                symmetricalMatrix1[1, 0] = 2;
                Console.ReadKey();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }
           
        }
        public void SparseSquareMatrixAgreement()
        {
            int d = 6;
            SparseSquareMatrix A = new SparseSquareMatrix(d);
            SquareMatrix B = new SquareMatrix(d);

            Random rng = new Random(1);
            for (int i = 0; i < 2 * d; i++) {
                int r = (int) Math.Floor(rng.NextDouble() * d);
                int c = (int) Math.Floor(rng.NextDouble() * d);
                A[r, c] = 2.0 * rng.NextDouble() - 1.0;
                B[r, c] = A[r, c];
            }

            RowVector u = new RowVector(d);
            ColumnVector v = new ColumnVector(d);
            for (int i = 0; i < d; i++) {
                u[i] = 2.0 * rng.NextDouble() - 1.0;
                v[i] = 2.0 * rng.NextDouble() - 1.0;
            }

            RowVector uA = u * A;
            RowVector uB = u * B;
            Assert.IsTrue(TestUtilities.IsNearlyEqual(uA, uB));

            ColumnVector Av = A * v;
            ColumnVector Bv = B * v;
            Assert.IsTrue(TestUtilities.IsNearlyEqual(Av, Bv));
        }
        static void Main(string[] args)
        {
            int[,] array = new int[3, 3] { { 1, 4, 5 }, { 52, 34, 3 }, { 6, 734, 8 } };                                                                                    
            SquareMatrix<int> m = new SquareMatrix<int>(array);
            Console.WriteLine(m.ToString());
            m.Change += IsChange;
            m[1, 2] = 100;
            Thread.Sleep(1000);
            Console.WriteLine();
            Console.WriteLine(m.ToString());

            int[,] arrayM = new int[3, 3] { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } };                                        
            Matrix<int> firstM = new SquareMatrix<int>(array);
            Console.WriteLine(firstM.ToString());
            Matrix<int> secondM = new SymmetricMatrix<int>(arrayM);
            Console.WriteLine(secondM.ToString());
            var result = WorkWithMatrix.Add( firstM,secondM, (a, b) => a + b);
            System.Console.WriteLine(result.ToString());

            
            int [,] arD1 = new int[3,3]{{1,0,0},{0,1,0},{0,0,1}};
            int[,] arD2 = new int[3, 3] { { 2, 0, 0 }, { 0, 2, 0 }, { 0, 0, 2 } };
            var fisrtDM = new DiagonalMatrix<int>(arD1);
            Console.WriteLine(fisrtDM.ToString());
            var secondDM = new DiagonalMatrix<int>(arD2);
            Console.WriteLine(secondDM.ToString());
            result = WorkWithMatrix.Add(fisrtDM, secondDM, (a, b) => a + b);
            System.Console.WriteLine(result.ToString());


            Console.ReadKey();
        }
 // matrix creation utilities
 public static SquareMatrix CreateSquareUnitMatrix(int n)
 {
     SquareMatrix I = new SquareMatrix(n);
     for (int i = 0; i < n; i++) {
         I[i, i] = 1.0;
     }
     return (I);
 }
Exemple #13
0
 void Awake()
 {
     Debug.Log ("SQUARE");
     squareMatrixScript = GameObject.FindGameObjectWithTag ("Block").GetComponent<SquareMatrix> ();
     gadgetsScript = GameObject.FindGameObjectWithTag ("Gadgets").GetComponent<Gadgets> ();
     initSquare ();
     initMazeMatrix ();
 }
 public void SquareMatrix_Create_Test()
 {
     int[,] matr = { { 1, 2, 3 }, 
                     { 1, 2, 3 }, 
                     { 1, 2, 3 } };
     SquareMatrix<int> matrix = new SquareMatrix<int>(matr);
     Assert.AreEqual(3, matrix[2, 2]);
 }
 public void SquareMatrixChangeEventTest()
 {
     GeneralMatrix<int> matrix = new SquareMatrix<int>(new int[3, 3] { { 1, 2, 3 }, { 2, 1, 2 }, { 3, 2, 1 } });
     Subscribe(matrix);
     matrix[0, 1] = 5;
     Unsubscribe(matrix);
     Assert.AreEqual<string>("SquareMatrix", message);
 }
        public void MatrixShouldReturnCorrectMatrixOfSize1()
        {
            var matrix = new SquareMatrix(1);
            matrix.RotatingWalkFill();
            var expected = new int[,] { { 1 } };

            Assert.IsTrue(this.MatricesAreEqual(expected, matrix.Matrix));
        }
        public void AddingDiagonalMatrix()
        {
            Matrix<int> m = new DiagonalMatrix<int>(new int[2][] { new int[2] { 1, 0 }, new int[2] { 0, 3 } });
            Matrix<int> m1 = new DiagonalMatrix<int>(new int[2][] { new int[2] { 1, 0 }, new int[2] { 0, 3 } });
            Matrix<int> m2 = m.Add(m1);
            Matrix<int> m3 = new SquareMatrix<int>(new int[2][] { new int[2] { 2, 0 }, new int[2] { 0, 6 } });

            Assert.IsTrue(m2.Equals(m3));
        }
        public void AddingSquareMatrix()
        {
            Matrix<int> m = new SquareMatrix<int>(new int[2][] { new int[2] { 1, 2 }, new int[2] { 2, 3 } });
            Matrix<int> m1 = new SquareMatrix<int>(new int[2][] { new int[2] { 1, 2 }, new int[2] { 2, 3 } });
            Matrix<int> m2 = m.Add(m1);
            Matrix<int> m3 = new SquareMatrix<int>(new int[2][] { new int[2] { 2, 4 }, new int[2] { 4, 6 } });

            Assert.IsTrue(m2.Equals(m3));
        }
 public void SquareMatrix_CtorException()
 {
     var first = new int[,]
     {
         {1, 2, 3},
         {4, 5, 6}
     };
     var lol = new SquareMatrix<int>(first);
 }
 public static SquareMatrix CreateHilbertMatrix(int n)
 {
     SquareMatrix H = new SquareMatrix(n);
     for (int r = 0; r < n; r++) {
         for (int c = 0; c < n; c++) {
             H[r, c] = 1.0 / (r + c + 1);
         }
     }
     return (H);
 }
 public void Indexer_iMoreOrder_ArgumentOutOfRangeException()
 {
     int[,] sourceArray = new int[2, 2] 
         {
             {1, 2},
             {3, 4}
         };
     SquareMatrix<int> matrix = new SquareMatrix<int>(sourceArray);
     int a = matrix[3, 0];
 }
Exemple #22
0
                /// <summary>
                /// Erstellt eine Einheitsmatrix mit der angegebenen Größe.
                /// </summary>
                /// <param name="size"></param>
                /// <returns></returns>
                public static SquareMatrix GetIdentity(int size)
                {
                    var m = new SquareMatrix(size); //Matrix erstellen

                    //Diagonale auf 1 setzen
                    for (int i = 0; i < size; i++)
                        m[i, i] = 1;

                    return m;
                }
        public void TestConstructor()
        {
            int[,] expected = new int[2, 2] {{1, 0}, {0, 0}};
            SquareMatrix<int> squareMatrix = new SquareMatrix<int>(expected);

            int[,] actual = squareMatrix.GetCoefs();

            Assert.AreEqual(2, squareMatrix.Dimension);
            CollectionAssert.AreEqual(expected, actual);
        }
        private static bool DiagonalDomination(SquareMatrix A)
        {
            bool key = true;

            for (int counter = 0; ((counter < A.Count) && (key)); counter++)
            {
                key = A[counter].Norm(VectorNormConstants.First) <= 2 * Math.Abs(A[counter][counter]);
            }

            return key;
        }
 public void Add_MatricesTypeWithoutOperatorPlus_ArithmeticException()
 {
     TypeWithoutOperatorPlus[,] sourceArray = new TypeWithoutOperatorPlus[,]
     {
         {new TypeWithoutOperatorPlus(1), new TypeWithoutOperatorPlus(2)},
         {new TypeWithoutOperatorPlus(3), new TypeWithoutOperatorPlus(4)},
     };
     SquareMatrix<TypeWithoutOperatorPlus> lhs = new SquareMatrix<TypeWithoutOperatorPlus>(sourceArray);
     SquareMatrix<TypeWithoutOperatorPlus> rhs = new SquareMatrix<TypeWithoutOperatorPlus>(sourceArray);
     lhs.Add(rhs);
 }
 public void SquareMatrix_IndexException()
 {
     var first = new int[,]
     {
         {1, 2, 3},
         {4, 5, 6},
         {7, 8, 9}
     };
     var lol = new SquareMatrix<int>(first);
     var integer = lol[-1, 2];
 }
        public void Equals_DiagonalMatrixEqualSquareMatrix_TrueReturned()
        {
            var a = new DiagonalMatrix<double>(new double[] {1,2});
            var b = new SquareMatrix<double>(new double[,]{
                {1,0},
                {0,2}});

            bool resul = a.Equals(b);

            Assert.AreEqual(true, resul);
        }
 /// <summary>
 /// Adds any two real, square matrices.
 /// </summary>
 /// <param name="A">The first matrix.</param>
 /// <param name="B">The second matrix.</param>
 /// <returns>The sum matrix A + B.</returns>
 /// <remarks>
 /// <para>Matrix addition is an O(N<sup>2</sup>) process.</para>
 /// </remarks>
 public static SquareMatrix operator +(AnySquareMatrix A, AnySquareMatrix B)
 {
     if (A == null) throw new ArgumentNullException("A");
     if (B == null) throw new ArgumentNullException("B");
     if (A.Dimension != B.Dimension) throw new DimensionMismatchException();
     SquareMatrix M = new SquareMatrix(A.Dimension);
     for (int r = 0; r < M.Dimension; r++) {
         for (int c = 0; c < M.Dimension; c++) {
             M[r, c] = A[r, c] + B[r, c];
         }
     }
     return (M);
 }
        public void Equals_SymmetricalMatrixEqualSquareMatrix_TrueReturned()
        {
            var a = new SymmetricalMatrix<int>(new int[,]{
                {1,1},
                {1,2}});
            var b = new SquareMatrix<int>(new int[,]{
                {1,1},
                {1,2}});

            bool result = a.Equals(b);

            Assert.AreEqual(true, result);
        }
        public BestInterpolationPolynomial(Vector x, Vector y, int power)
        {
            if (power > 0)
            {
                if (x.Length == y.Length)
                {
                    if (x.Length != 0)
                    {
                        SquareMatrix A = new SquareMatrix(power);
                        Vector b = new Vector(power);

                        for (int counter = 0; counter < power; counter++)
                        {
                            for (int counter1 = 0; counter1 < power; counter1++)
                            {
                                for (int counter2 = 0; counter2 < x.Length; counter2++)
                                {
                                    A[counter][counter1] += Math.Pow(x[counter2], counter + counter1);
                                }
                            }

                            for (int counter2 = 0; counter2 < x.Length; counter2++)
                            {
                                b[counter] += Math.Pow(x[counter2], counter) * y[counter2];
                            }
                        }
                        try
                        {
                            this.alpha = DirectMethods.GaussMethod(A, b);
                        }
                        catch (NoSolutionException error)
                        {
                            throw new IncorrectIncomingDataException("Error searching solutions for incoming vectors", error);
                        }
                    }
                    else
                    {
                        throw new IncorrectIncomingDataException("Length of incoming vectors could not be equal to zero.");
                    }
                }
                else
                {
                    throw new IncorrectIncomingDataException("Length of incoming vectors are not equal.");
                }
            }
            else
            {
                throw new IncorrectIncomingDataException("Incorrect power for polynomial was set.");
            }
        }
Exemple #31
0
        static void Main(string[] args)
        {
            BinarySearchTree <int> intTree = new BinarySearchTree <int>(5);

            intTree.Add(new[] { 8, 10, 3, 2, 7, 6 });
            foreach (var item in intTree.Inorder())
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            BinarySearchTree <int> intTree2 = new BinarySearchTree <int>(5, new IntComparer());

            intTree2.Add(new[] { 8, 10, 3, 2, 7, 6 });
            foreach (var item in intTree2.Inorder())
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            BinarySearchTree <string> stringTree = new BinarySearchTree <string>("5");

            stringTree.Add(new[] { "8", "9", "3", "2", "7", "6" });
            foreach (var item in stringTree.Inorder())
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            BinarySearchTree <string> stringTree2 = new BinarySearchTree <string>("5", new Logic.Comparers.StringComparer());

            stringTree2.Add(new[] { "8", "9", "3", "2", "7", "6" });
            foreach (var item in stringTree2.Inorder())
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            BinarySearchTree <Book> bookTree = new BinarySearchTree <Book>(new Book("Aaa", "Bbb", 102));

            bookTree.Add(new [] { new Book("Ccc", "Aaa", 1356), new Book("Zzz", "Qqq", 803), new Book("Lll", "Bbb", 1234) });
            foreach (var item in bookTree.Inorder())
            {
                Console.Write("\"{0}\", {1}, {2}.  ", item.Title, item.Author, item.Pages);
            }
            Console.WriteLine();

            BinarySearchTree <Book> bookTree2 = new BinarySearchTree <Book>(new Book("Aaa", "Bbb", 102), new BookComparer());

            bookTree2.Add(new[] { new Book("Ccc", "Aaa", 1356), new Book("Zzz", "Qqq", 803), new Book("Lll", "Bbb", 1234) });
            foreach (var item in bookTree2.Inorder())
            {
                Console.Write("\"{0}\", {1}, {2}.  ", item.Title, item.Author, item.Pages);
            }
            Console.WriteLine();

            BinarySearchTree <Point> pointTree = new BinarySearchTree <Point>(new Point(10, 12), new PointComparer());

            pointTree.Add(new[] { new Point(10, 6), new Point(11, 2), new Point(94, 1), new Point(5, 11), new Point(99, 0) });
            foreach (var item in pointTree.Inorder())
            {
                Console.Write("X:{0}; Y:{1}.   ", item.X, item.Y);
            }
            Console.WriteLine();


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            SymmetricMatrix <int> symmatr1 = new SymmetricMatrix <int>(new int[, ] {
                { 0, 1, 2 }, { 1, 0, 3 }, { 2, 3, 0 }
            });
            SymmetricMatrix <int> symmatr2 = new SymmetricMatrix <int>(new int[, ] {
                { 0, 1, 2 }, { 1, 0, 3 }, { 2, 3, 0 }
            });

            Console.WriteLine(symmatr1.Add(symmatr2, (a, b) => a + b));

            SquareMatrix <int> sqmatr = new SquareMatrix <int>(new int[, ] {
                { 2, 1, 7 }, { 1, 0, 3 }, { 2, 3, 8 }
            });

            Console.WriteLine(sqmatr.Add(symmatr2, (a, b) => a + b));

            DiagonalMatrix <int> dmatr = new DiagonalMatrix <int>(new int[, ] {
                { 0, 1, 7 }, { 1, 0, 3 }, { 2, 3, 0 }
            });

            Console.WriteLine(dmatr.Add(symmatr2, (a, b) => a + b));
        }
Exemple #32
0
        private bool IsRestart(ref Solution solution, ColumnVector fitnesses, double tolX, CMAState cmaState)
        {
            bool isAllNaN = fitnesses.All(x => double.IsNaN(x) || double.IsInfinity(x));

            if (isAllNaN)
            {
                return(true);
            }

            // Stop if the condition number of the covariance matrix
            //exceeds 1014 (conditioncov).
            bool isCConditionNumberTooHigh = false;

            if ((Utilities.Diag(cmaState.C, x => x).ToArray().Max() / Utilities.Diag(cmaState.C, x => x).ToArray().Min()) > 1e14)
            {
                isCConditionNumberTooHigh = true;
            }

            if (isCConditionNumberTooHigh)
            {
                return(true);
            }

            if (solution.History == null)
            {
                solution.History = new Queue <double>();
            }

            //Stop if the range of the best objective function values
            //of the last 10 + [30n/lambda] generations is zero
            //(equalfunvalhist), or the range of these function
            //values and all function values of the recent generation
            //is below Tolfun= 10^-12.
            solution.History.Enqueue(fitnesses[0]);
            if (solution.History.Count > (10.0 + ((30.0 * cmaState.p.N) / cmaState.p.Lambda)))
            {
                solution.History.Dequeue();
            }

            bool isObjectiveFunctionRangeTooLow = (solution.History.Count == (int)(10.0 + ((30.0 * cmaState.p.N) / cmaState.p.Lambda))) &&
                                                  ((solution.History.Max() == solution.History.Min()) ||
                                                   (((solution.History.Max() - solution.History.Min()) < ObjectiveFunctionTolerance) && ((fitnesses.Max() - fitnesses.Min()) < ObjectiveFunctionTolerance)));

            if (isObjectiveFunctionRangeTooLow)
            {
                return(true);
            }


            // Stop if the standard deviation of the normal distribution
            //is smaller than TolX in all coordinates and igma]pc
            //(the evolution path from Eq. 2 in [3]) is smaller than
            //TolX in all components. We set TolX= 10^-12*[sigma]^(0).
            bool isStandardDeviationTooSmall = (Utilities.IsTrueForAll(cmaState.C, x => Math.Abs(x) < tolX) && cmaState.ps.All(x => Math.Abs(x) < tolX));

            if (isStandardDeviationTooSmall)
            {
                return(true);
            }

            // Stop if adding a 0.1-standard deviation vector in
            //a principal axis direction of C^(g) does not change
            //<x[vector]>w^(g) (noeffectaxis)3
            int          ith      = (cmaState.gen % cmaState.p.N);
            ColumnVector tmpXmean = (cmaState.mean + 0.1 * cmaState.sigma * cmaState.B * new ColumnVector(cmaState.d));

            bool isNoEffectAxis = false;

            if (ith < tmpXmean.Dimension)
            {
                isNoEffectAxis = (tmpXmean[ith] == cmaState.mean[ith]);
            }

            if (isNoEffectAxis)
            {
                return(true);
            }

            // Stop if adding 0.2-standard deviation in each coordinate
            //does change <x[vector]>w^(g) (noeffectcoord).
            SquareMatrix testC = 0.2 * cmaState.sigma * cmaState.C;
            SquareMatrix vectors;
            SquareMatrix values;

            Utilities.EigAlgLib(testC, out vectors, out values, 1, isGetLower: false);
            ColumnVector colValues = Utilities.Diag(values, x => Math.Sqrt(Math.Abs(x)));

            tmpXmean = (cmaState.mean + cmaState.sigma * vectors * colValues);
            bool isNoEffectCoord = true;

            for (int i = 0; i < cmaState.mean.Dimension; i++)
            {
                if (cmaState.mean[i] != tmpXmean[i])
                {
                    isNoEffectCoord = false;
                    break;
                }
            }

            if (isNoEffectCoord)
            {
                return(true);
            }

            return(false);
        }
 /// <summary>
 /// Initials the new summation decorator.
 /// </summary>
 /// <param name="matrix">The matrix.</param>
 public SummDecorator(SquareMatrix <T> matrix) : base(matrix)
 {
 }
Exemple #34
0
 public ComplexSquareMatrix(SquareMatrix re, SquareMatrix im)
 {
     Re = re;
     Im = im;
 }
Exemple #35
0
        public void MultiExpressionTest()
        {
            SquareMatrix <int> sm1 = new SquareMatrix <int>(2, 2)
            {
                new Vector <int>(2)
                {
                    1, 0
                },
                new Vector <int>(2)
                {
                    1, 1
                }
            };

            SquareMatrix <int> sm2 = new SquareMatrix <int>(2, 2)
            {
                new Vector <int>(2)
                {
                    1, 0
                },
                new Vector <int>(2)
                {
                    0, 1
                }
            };

            SquareMatrix <int> sm3 = new SquareMatrix <int>(2, 2)
            {
                new Vector <int>(2)
                {
                    1, 1
                },
                new Vector <int>(2)
                {
                    1, 0
                }
            };

            SquareMatrix <int> sm4 = new SquareMatrix <int>(2, 2)
            {
                new Vector <int>(2)
                {
                    0, 1
                },
                new Vector <int>(2)
                {
                    0, 0
                }
            };

            var sm5 = sm1 * (sm2 + sm3) + sm2 * (sm1 + sm3);

            Assert.AreEqual(new Vector <int>(2)
            {
                4, 2
            }, sm5[0]);
            Assert.AreEqual(new Vector <int>(2)
            {
                5, 3
            }, sm5[1]);
        }
Exemple #36
0
        static void Main(string[] args)
        {
            #region create and initialize sMatrix= SquareMatrix<object>
            SquareMatrix <object> sMatrix = new SquareMatrix <object>(size);
            sMatrix.changed += (object o, int i, int j) => Console.WriteLine("a[" + i + "," + j + "] = " + ((AbstractMatrix <object>)o)[i, j]);
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    sMatrix[i, j] = (i + 1) * 5.3 + j;
                }
            }
            sMatrix[3, 4] = "asdfasdf";
            #endregion
            SumMatrix(sMatrix, sMatrix, "--=Sum of sMatrix=--");

            Console.WriteLine();
            Console.WriteLine("Symmetric matrix initialize");
            #region create and initialize symMatrix= SymmetricMatrix<string>
            SymmetricMatrix <string> symMatrix = new SymmetricMatrix <string>(size);
            symMatrix.changed += (object o, int i, int j) =>
            {
                Console.WriteLine("a[" + i + "," + j + "] = " + ((AbstractMatrix <string>)o)[i, j]);
                if (i != j)
                {
                    Console.WriteLine("a[" + j + "," + i + "] = " + ((AbstractMatrix <string>)o)[j, i]);
                }
            };
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    symMatrix[i, j] = "8" + i + j;
                }
            }
            #endregion

            ShowMatrix(symMatrix, "Symmetric matrix");
            ShowMatrix(sMatrix, "Square matrix");
            SumMatrix(sMatrix, symMatrix, "--=Sum of sMatrix and symMatrix=--");

            Console.WriteLine();
            Console.WriteLine("Diagonal matrix initialize");
            #region create and initialize dmatrix= DiagonalMatrix<List<object>>
            DiagonalMatrix <List <object> > dMatrix = new DiagonalMatrix <List <object> >(size);
            symMatrix.changed += (object o, int i, int j) =>
            {
                Console.WriteLine("a[" + i + "," + j + "] = " + ((AbstractMatrix <List <object> >)o)[i, j]);
                if (i != j)
                {
                    Console.WriteLine("a[" + j + "," + i + "] = " + ((AbstractMatrix <List <object> >)o)[j, i]);
                }
            };
            for (int i = 0; i < size; i++)
            {
                dMatrix[i, i] = new List <object>()
                {
                    '8', i, i *i
                };
            }
            #endregion


            SumMatrix(symMatrix, dMatrix, "--=Sum of symMatrix and dMatrix=--");
            SumMatrix(dMatrix, symMatrix, "--=Sum of symMatrix and dMatrix=--");

            #region exeptions
            try
            {
                SumMatrix(sMatrix, dMatrix, "--=Sum of sMatrix and dMatrix=--"); //exeption
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            #endregion

            Console.WriteLine();
            Console.WriteLine("Double and int matrix initialize");
            #region create and initialize a= SquareMatrix<double>
            SquareMatrix <double> a = new SquareMatrix <double>(size);
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    a[i, j] = (i + 1) * 5.3 + j;
                }
            }
            #endregion

            #region create and initialize b= SquareMatrix<int>
            SquareMatrix <int> b = new SquareMatrix <int>(size);
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    b[i, j] = (i + 1) + j;
                }
            }
            #endregion

            SumMatrix(a, b, "--=Sum of a and b=--");
            try
            {
                SumMatrix(b, a, "--=Sum of a and b=--"); //exeption
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void DeterminateTest()
        {
            //#7
            SquareMatrix <double> M1 = new SquareMatrix <double>(3)
            {
                new Vector <double>(3)
                {
                    5, 3, 5
                },
                new Vector <double>(3)
                {
                    0, -3, 2
                },
                new Vector <double>(3)
                {
                    -2, 1, 3
                }
            };

            Assert.AreEqual(-97, SquareMatrix <double> .Determinate(M1));

            //#8
            SquareMatrix <double> M2 = new SquareMatrix <double>(3)
            {
                new Vector <double>(3)
                {
                    2, 3, 5
                },
                new Vector <double>(3)
                {
                    4, 6, 10
                },
                new Vector <double>(3)
                {
                    -2, 1, 3
                }
            };

            Assert.AreEqual(0, SquareMatrix <double> .Determinate(M2));

            //#9
            SquareMatrix <double> M3 = new SquareMatrix <double>(2)
            {
                new Vector <double>(2)
                {
                    2, 3
                },
                new Vector <double>(2)
                {
                    -4, 6
                }
            };

            Assert.AreEqual(24, SquareMatrix <double> .Determinate(M3));

            //#10
            SquareMatrix <double> M4 = new SquareMatrix <double>(1)
            {
                new Vector <double>(1)
                {
                    2
                }
            };

            Assert.AreEqual(2, SquareMatrix <double> .Determinate(M4));

            //#11
            SquareMatrix <double> M5 = new SquareMatrix <double>(4)
            {
                new Vector <double>(4)
                {
                    1, 3, 2, 4
                },
                new Vector <double>(4)
                {
                    10, -12, 1, 0
                },
                new Vector <double>(4)
                {
                    1, 7, 0, -6
                },
                new Vector <double>(4)
                {
                    -2, 3, 0, 1
                }
            };

            Assert.AreEqual(110, SquareMatrix <double> .Determinate(M5));

            //#12
            SquareMatrix <double> M6 = new SquareMatrix <double>(2)
            {
                new Vector <double>(2)
                {
                    5.5, 2.1
                },
                new Vector <double>(2)
                {
                    2, 3.4
                }
            };

            Assert.AreEqual(14.5, SquareMatrix <double> .Determinate(M6));
        }
Exemple #38
0
        public static void Main(string[] args)
        {
            Queue <int> queue = new Queue <int>(7);

            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Enqueue(4);
            queue.Enqueue(5);
            queue.Enqueue(6);
            queue.Enqueue(7);
            queue.Enqueue(8);
            queue.Enqueue(9);
            queue.Enqueue(10);
            queue.Enqueue(11);

            foreach (var i in queue)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine(" ");

            queue.Clear();

            queue.Enqueue(3);
            queue.Enqueue(5);
            queue.Enqueue(6);
            queue.Enqueue(7);

            foreach (var i in queue)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine(" ");

            Console.WriteLine(queue.Peek());

            SquareMatrix <int> a = new SquareMatrix <int>(new int[] { 2, 4, 1, 4, 5, 5, 6, 3, 2 });

            Console.WriteLine("-------");

            foreach (var item in a)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("-------");
            Console.WriteLine(a.GetValue(1, 1));
            a.SetValue(2, 2, 78);
            Console.WriteLine("-------");

            foreach (var item in a)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(a.GetValue(2, 2));

            DiagonalMatrix <int> a1 = new DiagonalMatrix <int>(new int[] { 2, 4, 1, 4 });

            foreach (var item in a1)
            {
                Console.WriteLine(item);
            }

            SymmetricMatrix <int> a2 = new SymmetricMatrix <int>(new int[][] { new int[] { 1, 2, 3 } });

            foreach (var item in a2)
            {
                Console.WriteLine(item);
            }

            SquareMatrix <int>   b1 = new SquareMatrix <int>(new int[] { 2, 4, 1, 4, 5, 5, 6, 3, 2 });
            DiagonalMatrix <int> b2 = new DiagonalMatrix <int>(new int[] { 2, 4, 1 });
            var c = MatrixSum.Sum(b1, b2);

            foreach (var item in c)
            {
                Console.WriteLine(item);
            }
        }
Exemple #39
0
        /// <summary>
        /// Copy values from array to square matrix
        /// </summary>
        /// <typeparam name="T"> Type of elements </typeparam>
        /// <param name="matrix"> Matrix for copying in </param>
        /// <param name="values"> Values for copying out </param>
        /// <exception cref="ArgumentNullException"> If values is null </exception>
        /// <exception cref="ArgumentException"> If values lenght is more than lenght of matrix </exception>
        public static void Copy <T>(this SquareMatrix <T> matrix, T[] values)
        {
            Validate(matrix, values);

            CopyToMatrix(matrix, values);
        }
        private static void Main(string[] args)
        {
            // define squares
            BoardSpace[] spaces = new BoardSpace[] {
                new BoardSpace("Go", 0.0, Double.PositiveInfinity),
                new BoardSpace("Mediterranean Avenue", 2.0, 60.0),
                new BoardSpace("Community Chest", 0.0, Double.PositiveInfinity),
                new BoardSpace("Baltic Avenue", 4.0, 60.0),
                new BoardSpace("Income Tax", 0.0, Double.PositiveInfinity),
                new BoardSpace("Reading Railroad", 25.0, 200.0),
                new BoardSpace("Oriental Avenue", 6.0, 100.0),
                new BoardSpace("Chance", 0.0, Double.PositiveInfinity),
                new BoardSpace("Vermont Avenue", 6.0, 100.0),
                new BoardSpace("Connecticut Avenue", 8.0, 120.0),
                new BoardSpace("Jail", 0.0, Double.PositiveInfinity),
                new BoardSpace("St. Charles Place", 10.0, 140.0),
                new BoardSpace("Electric Company", 4.0 * 6.0, 150.0),
                new BoardSpace("States Avenue", 10.0, 140.0),
                new BoardSpace("Virginia Avenue", 12.0, 160.0),
                new BoardSpace("Pennsylvania Railroad", 25.0, 200.0),
                new BoardSpace("St. James Place", 14.0, 180.0),
                new BoardSpace("Community Chest", 0.0, Double.PositiveInfinity),
                new BoardSpace("Tennessee Avenue", 14.0, 180.0),
                new BoardSpace("New York Avenue", 16.0, 200.0),
                new BoardSpace("Free Parking", 0.0, Double.PositiveInfinity),
                new BoardSpace("Kentucky Avenue", 18.0, 220.0),
                new BoardSpace("Chance", 0.0, Double.PositiveInfinity),
                new BoardSpace("Indiana Avenue", 18.0, 220.0),
                new BoardSpace("Illinois Avenue", 20.0, 240.0),
                new BoardSpace("B & O Railroad", 25.0, 200.0),
                new BoardSpace("Atlantic Avenue", 22.0, 260.0),
                new BoardSpace("Ventnor Avenue", 22.0, 260.0),
                new BoardSpace("Water Works", 4.0 * 6.0, 150.0),
                new BoardSpace("Marvin Gardens", 24.0, 280.0),
                new BoardSpace("Go To Jail", 0.0, Double.PositiveInfinity),
                new BoardSpace("Pacific Avenue", 26.0, 300.0),
                new BoardSpace("North Carolina Avenue", 26.0, 300.0),
                new BoardSpace("Community Chest", 0.0, Double.PositiveInfinity),
                new BoardSpace("Pennsylvania Avenue", 28.0, 320.0),
                new BoardSpace("Short Line", 25.0, 200.0),
                new BoardSpace("Chance", 0.0, Double.PositiveInfinity),
                new BoardSpace("Park Place", 35.0, 350.0),
                new BoardSpace("Luxury Tax", 0.0, Double.PositiveInfinity),
                new BoardSpace("Boardwalk", 50.0, 400.0)
            };

            // number of squares
            int n = spaces.Length;

            // compute the transition matrix which takes the dice roll
            // into account: Moves us ahead by two spaces with
            // probability 1/36 (“snake-eyes”), three spaces with
            // probability 2/36, and so on up to twelve spaces with
            // probability 1/36 (“double-sixes”), etc.
            SquareMatrix R = new SquareMatrix(n);

            for (int c = 0; c < n; c++)
            {
                R[(c + 2) % n, c]  = 1.0 / 36.0;
                R[(c + 3) % n, c]  = 2.0 / 36.0;
                R[(c + 4) % n, c]  = 3.0 / 36.0;
                R[(c + 5) % n, c]  = 4.0 / 36.0;
                R[(c + 6) % n, c]  = 5.0 / 36.0;
                R[(c + 7) % n, c]  = 6.0 / 36.0;
                R[(c + 8) % n, c]  = 5.0 / 36.0;
                R[(c + 9) % n, c]  = 4.0 / 36.0;
                R[(c + 10) % n, c] = 3.0 / 36.0;
                R[(c + 11) % n, c] = 2.0 / 36.0;
                R[(c + 12) % n, c] = 1.0 / 36.0;
            }

            // compute the special matrix, which takes board into account:
            // The column for space 30, “Go To Jail”, transitions with
            // certainty to space 10, the jail.
            // A token that lands on a community chest space sometimes
            // transitions to go and sometimes transitions to jail, but
            // most often just stays put
            SquareMatrix S = new SquareMatrix(n);

            for (int c = 0; c < n; c++)
            {
                if (c == 30)
                {
                    // go to jail
                    S[10, 30] = 1.0;
                }
                else if ((c == 7) || (c == 22) || (c == 36))
                {
                    // chance
                    // advance to go
                    S[0, c] = 1.0 / 16.0;
                    // advance to illinois avenue
                    S[24, c] = 1.0 / 16.0;
                    // take a walk on the boardwalk
                    S[39, c] = 1.0 / 16.0;
                    // go to jail
                    S[10, c] = 1.0 / 16.0;
                    // take a ride on the reading
                    S[5, c] = 1.0 / 16.0;
                    // advance to St. Charles place
                    S[11, c] = 1.0 / 16.0;
                    // go back 3 spaces
                    S[(c - 3) % S.Dimension, c] = 1.0 / 16.0;
                    // advance token to the nearest utility
                    if ((c < 12) || (c > 28))
                    {
                        S[12, c] = 1.0 / 16.0;
                    }
                    else
                    {
                        S[28, c] = 1.0 / 16.0;
                    }
                    // advance token to the nearest railroad
                    if (c < 5)
                    {
                        S[5, c] += 1.0 / 16.0;
                    }
                    else if (c < 15)
                    {
                        S[15, c] = 1.0 / 16.0;
                    }
                    else if (c < 25)
                    {
                        S[25, c] = 1.0 / 16.0;
                    }
                    else if (c < 35)
                    {
                        S[35, c] = 1.0 / 16.0;
                    }
                    else
                    {
                        S[5, c] += 1.0 / 16.0;
                    }
                    // stay put
                    S[c, c] = 7.0 / 16.0;
                }
                else if ((c == 2) || (c == 17) || (c == 33))
                {
                    // community chest
                    // advance to go
                    S[0, c] = 1.0 / 16.0;
                    // go to jail
                    S[10, c] = 1.0 / 16.0;
                    // stay put
                    S[c, c] = 14.0 / 16.0;
                }
                else
                {
                    // all other spaces are no-ops
                    S[c, c] = 1.0;
                }
            }

            // compute the complete transition matrix
            SquareMatrix P = S * R;

            // verify Markov conditions
            for (int c = 0; c < P.Dimension; c++)
            {
                double sr = 0.0;
                for (int r = 0; r < P.Dimension; r++)
                {
                    sr += P[r, c];
                }
                Debug.Assert(Math.Abs(sr - 1.0) < 1.0e-15);
            }

            // An alternative now is to begin with some initial state vector
            // guess, and repeatedly apply P until the resultant vector
            // no longer changes. The resultant vector will be the dominant
            // eigenvector. That's how PageRank is evaluated by Google,
            // using MapReduce.

            // Another alternative is to compute the eigenvalues and
            // eigenvectors of the transition matrix
            ComplexEigensystem E = P.Eigensystem();

            // get the dominant eigenvector: The one with the largest
            // eigenvalue
            Complex         e = -1.0;
            IList <Complex> v = null;

            for (int i = 0; i < E.Dimension; i++)
            {
                Complex ei = E.Eigenvalue(i);
                if (ComplexMath.Abs(ei) > ComplexMath.Abs(e))
                {
                    e = ei;
                    v = E.Eigenvector(i);
                }
            }

            // verify that it has eigenvalue 1 and is real
            Debug.Assert(Math.Abs(e.Re - 1.0) < 1.0e-15);
            Debug.Assert(e.Im == 0.0);
            for (int i = 0; i < n; i++)
            {
                Debug.Assert(v[i].Im == 0.0);
            }

            // normalize the probabilities
            double sv = 0.0;

            for (int i = 0; i < E.Dimension; i++)
            {
                sv += v[i].Re;
            }
            double[] p = new double[E.Dimension];
            for (int i = 0; i < E.Dimension; i++)
            {
                p[i] = v[i].Re / sv;
            }

            // Having found the dominant eigenvector, we can examine its components
            // to find the long-run relative probabilities of a token landing on each
            // space.
            // Print the probabilities

            // First column: Which rent-generating properties are most landed upon

            // Second column: A rent-seeking player would be willing to accept a slightly
            // less frequently landed upon space, if it generates a much higher rent when
            // landed upon --> Multiply the landing probability per turn by the rent per landing

            // Third column: A clever investor cares not only about cash flow, but
            // also about the return on his investment (ROI), that is the rent generated
            // per dollar paid --> Divide the rent per turn by the property price

            for (int i = 0; i < n; i++)
            {
                Console.WriteLine("{0,-24} {1:f4} {2:f4} {3:f4}", spaces[i].Name, p[i], p[i] * spaces[i].Rent, p[i] * spaces[i].Rent / spaces[i].Price);
            }

            // First column: Which rent-generating properties are most landed upon:
            // Illinois Avenue (3.2%) and New York Avenue (3.1%), followed by Tennessee, the Reading, and the B & O (2.9% each).

            // Second column: A rent-seeking player would be willing to accept a slightly less frequently landed upon space,
            // if it generates a much higher rent when landed upon. To know which spaces maximize rent per turn,
            // we need to multiply the landing probability per turn by the rent per landing.
            // Boardwalk ($1.32/turn) is far and away the most rent-generating property to own

            // Third column: Finally, a clever investor cares not only about cash flow, but also about the return on his
            // investment (ROI), that is the rent generated per dollar paid. Dividing the rent per turn by
            // the property price changes the picture yet again. By this metric, the best values on the board
            // are the utilities, followed by the railways.

            Console.ReadLine();
        }
Exemple #41
0
 private static SquareMatrix <T> Sum <T>(SquareMatrix <T> matr1, SquareMatrix <T> matr2, Func <T, T, T> sumFunc)
     where T : struct
 {
     return(new SquareMatrix <T>(AddMatrixes(matr1, matr2, sumFunc)));
 }
Exemple #42
0
        public void ReplaceColumnTest()
        {
            SquareMatrix <double> expectedMatrix1 = new SquareMatrix <double>(3)
            {
                new Vector <double>(3)
                {
                    2, 2, 3
                },
                new Vector <double>(3)
                {
                    2, 5, 6
                },
                new Vector <double>(3)
                {
                    2, 8, 9
                }
            };
            SquareMatrix <double> matrix1 = new SquareMatrix <double>(3)
            {
                new Vector <double>(3)
                {
                    1, 2, 3
                },
                new Vector <double>(3)
                {
                    4, 5, 6
                },
                new Vector <double>(3)
                {
                    7, 8, 9
                }
            };

            Assert.AreEqual(expectedMatrix1, matrix1.ReplaceColumn(new Vector <double>(3)
            {
                2, 2, 2
            }, 0));
            SquareMatrix <int> expectedMatrix2 = new SquareMatrix <int>(4)
            {
                new Vector <int>(4)
                {
                    5, 6, 0, 9
                },
                new Vector <int>(4)
                {
                    5, 4, 0, 3
                },
                new Vector <int>(4)
                {
                    1, 2, 0, 2
                },
                new Vector <int>(4)
                {
                    7, 8, 0, 3
                }
            };
            SquareMatrix <int> matrix2 = new SquareMatrix <int>(4)
            {
                new Vector <int>(4)
                {
                    5, 6, 7, 9
                },
                new Vector <int>(4)
                {
                    5, 4, 2, 3
                },
                new Vector <int>(4)
                {
                    1, 2, 2, 2
                },
                new Vector <int>(4)
                {
                    7, 8, 1, 3
                }
            };

            Assert.AreEqual(expectedMatrix2, matrix2.ReplaceColumn(new Vector <int>(4)
            {
                0, 0, 0, 0
            }, 2));
        }
Exemple #43
0
        public void TestCorrelatedSimulation()//for Hybrid Methode
        {
            StreamWriter Z_text  = new StreamWriter("C:\\Users\\Marouane\\Desktop\\M2IF\\rough volatility\\FileZ.txt");
            StreamWriter Z1_text = new StreamWriter("C:\\Users\\Marouane\\Desktop\\M2IF\\rough volatility\\FileZ1.txt");
            StreamWriter Z2_text = new StreamWriter("C:\\Users\\Marouane\\Desktop\\M2IF\\rough volatility\\FileZ2.txt");

            rBergomiVIXfuture model = new rBergomiVIXfuture();
            int    n    = 500;
            double T    = 0.5;
            Grid   grid = new Grid(0, T, (int)Math.Abs(T * n));

            //Correl
            SymmetricMatrix correl = model.MakeCorrel(n, grid);

            SquareMatrix choleskyCorrel = correl.CholeskyDecomposition().SquareRootMatrix();

            //Gaussian Simulator
            var    simulator = new GaussianSimulator();
            double mc        = 1.0E5;

            ColumnVector Z_test   = new ColumnVector((int)mc);
            ColumnVector Z_test_1 = new ColumnVector((int)mc);
            ColumnVector Z_test_2 = new ColumnVector((int)mc);
            ColumnVector G        = new ColumnVector((int)mc);

            for (int i = 1; i <= mc; i++)
            {
                DoubleVector      Z   = new DoubleVector(grid.get_timeNmbrStep());
                RectangularMatrix Z_k = new RectangularMatrix(2, grid.get_timeNmbrStep());

                HybridScheme hybridscheme = new HybridScheme(choleskyCorrel, grid, 2, 0.07);

                hybridscheme.SimulateCorrelated(Z, Z_k);//Simulate 3 Correlated Gaussians Z_i; Z_k_{1,i}; Z_k_{2,i}  i:= 0, ..., n_T
                int mid = (int)grid.get_timeNmbrStep() / 2;

                G[i - 1] = simulator.Next();

                Z_test[i - 1]   = Z[mid];
                Z_test_1[i - 1] = Z_k[0, mid];
                Z_test_2[i - 1] = Z_k[1, mid];

                string Ztext_  = "";
                string Ztext1_ = "";
                string Ztext2_ = "";
                for (int k = 0; k < Z.RowCount; k++)
                {
                    Ztext_  += (Z[k].ToString() + "; ");
                    Ztext1_ += (Z_k[0, k].ToString() + "; ");
                    Ztext2_ += (Z_k[1, k].ToString() + "; ");
                }
                Z_text.WriteLine(Ztext_);
                Z1_text.WriteLine(Ztext1_);
                Z2_text.WriteLine(Ztext2_);
            }

            Z_text.Close();
            Z1_text.Close();
            Z2_text.Close();

            BivariateSample mybivariate = new BivariateSample();

            mybivariate.Add(Z_test, Z_test_2);

            double correlcoef = mybivariate.CorrelationCoefficient;
            double correlreal = correl[2, 0];

            Sample mysample = new Sample(Z_test);
            double mean     = mysample.Mean;     //must be =0
            double variance = mysample.Variance; //must be =1/n
            var    result   = mysample.KolmogorovSmirnovTest(new NormalDistribution());

            Sample mysampleG = new Sample(G);
            var    result2   = mysampleG.KolmogorovSmirnovTest(new NormalDistribution());
        }
Exemple #44
0
 protected override void Visit(SquareMatrix <T> matrix)
 {
     this.ValidateMatrix(matrix);
     T[,] array = matrix.ToArray();
     this.NormalizeResultType(matrix, () => new SquareMatrix <T>(array));
 }
        public void InverseTest()
        {
            //#13
            SquareMatrix <double> M1 = new SquareMatrix <double>(2)
            {
                new Vector <double>(2)
                {
                    4, 7
                },
                new Vector <double>(2)
                {
                    4, 8
                }
            };

            M1 = SquareMatrix <double> .Inverse(M1);

            SquareMatrix <double> M_1 = new SquareMatrix <double>(2)
            {
                new Vector <double>(2)
                {
                    2, -1.75
                },
                new Vector <double>(2)
                {
                    -1, 1
                }
            };

            for (int i = 0; i < M1.RowCount; i++)
            {
                for (int j = 0; j < M1.RowCount; j++)
                {
                    Assert.AreEqual(M_1[i, j], M1[i, j]);
                }
            }

            //#14
            SquareMatrix <double> M2 = new SquareMatrix <double>(3)
            {
                new Vector <double>(3)
                {
                    2, 4, 8
                },
                new Vector <double>(3)
                {
                    4, 2, 2
                },
                new Vector <double>(3)
                {
                    -2, 4, 4
                }
            };

            M2 = SquareMatrix <double> .Inverse(M2);

            SquareMatrix <double> M_2 = new SquareMatrix <double>(3)
            {
                new Vector <double>(3)
                {
                    0, 0.2, -0.1
                },
                new Vector <double>(3)
                {
                    -0.25, 0.3, 0.35
                },
                new Vector <double>(3)
                {
                    0.25, -0.2, -0.15
                }
            };

            for (int i = 0; i < M2.RowCount; i++)
            {
                for (int j = 0; j < M2.RowCount; j++)
                {
                    Assert.AreEqual(M_2[i, j], M2[i, j]);
                }
            }
        }
 public void MatrixShouldThrowExceptionWhenSizeIsLessThanMinimum()
 {
     var matrix = new SquareMatrix(0);
 }
        public static QuadraticInterpolationModel Construct(double[][] points, double[] values)
        {
            int m = points.Length;
            int d = points[0].Length;

            // find the minimum point, use it as the origin
            int iMin = 0; double fMin = values[0];

            for (int i = 1; i < values.Length; i++)
            {
                if (values[i] < fMin)
                {
                    iMin = i; fMin = values[i];
                }
            }

            SquareMatrix A = new SquareMatrix(m);
            int          c = 0;

            for (int r = 0; r < m; r++)
            {
                A[r, 0] = 1.0;
            }
            for (int i = 0; i < d; i++)
            {
                c++;
                for (int r = 0; r < m; r++)
                {
                    A[r, c] = points[r][i] - points[iMin][i];
                }
            }
            for (int i = 0; i < d; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    c++;
                    for (int r = 0; r < m; r++)
                    {
                        A[r, c] = (points[r][i] - points[iMin][i]) * (points[r][j] - points[iMin][j]);
                    }
                }
            }
            ColumnVector b = new ColumnVector(values);

            SquareQRDecomposition QR = A.QRDecomposition();
            ColumnVector          a  = QR.Solve(b);

            QuadraticInterpolationModel model = new QuadraticInterpolationModel();

            model.d      = d;
            model.origin = points[iMin];
            model.f0     = a[0];
            model.g      = new double[d];
            c            = 0;
            for (int i = 0; i < d; i++)
            {
                c++;
                model.g[i] = a[c];
            }
            model.h = new double[d][];
            for (int i = 0; i < d; i++)
            {
                model.h[i] = new double[d];
            }
            for (int i = 0; i < d; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    c++;
                    if (i == j)
                    {
                        model.h[i][j] = 2.0 * a[c];
                    }
                    else
                    {
                        model.h[i][j] = a[c];
                        model.h[j][i] = a[c];
                    }
                }
            }

            return(model);
        }
 public void MatrixShouldThrowExceptionWhenSizeIsBiggerThanMaximum()
 {
     var matrix = new SquareMatrix(101);
 }
Exemple #49
0
        public void GetHashCodeTest()
        {
            SquareMatrix <int> sm1 = new SquareMatrix <int>(2, 2)
            {
                new Vector <int>(2)
                {
                    2, 3
                },
                new Vector <int>(2)
                {
                    3, 4
                }
            };

            SquareMatrix <int> sm2 = new SquareMatrix <int>(2, 2)
            {
                new Vector <int>(2)
                {
                    2, 3
                },
                new Vector <int>(2)
                {
                    3, 4
                }
            };

            Assert.AreEqual(sm1.GetHashCode(), sm2.GetHashCode());

            SquareMatrix <int> sm3 = new SquareMatrix <int>(3, 3)
            {
                new Vector <int>(3)
                {
                    3, 2, 4
                },
                new Vector <int>(3)
                {
                    4, 5, 6
                },
                new Vector <int>(3)
                {
                    1, 6, 7
                }
            };

            SquareMatrix <int> sm4 = new SquareMatrix <int>(3, 3)
            {
                new Vector <int>(3)
                {
                    1, 4, 5
                },
                new Vector <int>(3)
                {
                    3, 5, 6
                },
                new Vector <int>(3)
                {
                    7, 8, 9
                }
            };

            Assert.AreNotEqual(sm3.GetHashCode(), sm4.GetHashCode());
        }
Exemple #50
0
        private void GetParameters()
        {
            // A x^2 + B x y + C y^2 + D x + E y + F = 0
            double[] par       = new double[6];
            int      numPoints = pointList.Count;

            if (numPoints > 2)
            {
                Matrix       D1 = new Matrix(numPoints, 3);
                Matrix       D2 = new Matrix(numPoints, 3);
                SquareMatrix S1 = new SquareMatrix(3);
                SquareMatrix S2 = new SquareMatrix(3);
                SquareMatrix S3 = new SquareMatrix(3);
                SquareMatrix T  = new SquareMatrix(3);
                SquareMatrix M  = new SquareMatrix(3);
                SquareMatrix C1 = new SquareMatrix(3);
                Matrix       a1 = new Matrix(3, 1);
                Matrix       a2 = new Matrix(3, 1);
                Matrix       temp;

                C1[0, 0] = 0;
                C1[0, 1] = 0;
                C1[0, 2] = 0.5;
                C1[1, 0] = 0;
                C1[1, 1] = -1;
                C1[1, 2] = 0;
                C1[2, 0] = 0.5;
                C1[2, 1] = 0;
                C1[2, 2] = 0;

                //2 D1 = [x .ˆ 2, x .* y, y .ˆ 2]; % quadratic part of the design matrix
                //3 D2 = [x, y, ones(size(x))]; % linear part of the design matrix
                for (int xx = 0; xx < numPoints; xx++)
                {
                    Point p = pointList[xx];
                    D1[xx, 0] = p.X * p.X;
                    D1[xx, 1] = p.X * p.Y;
                    D1[xx, 2] = p.Y * p.Y;

                    D2[xx, 0] = p.X;
                    D2[xx, 1] = p.Y;
                    D2[xx, 2] = 1;
                }

                //4 S1 = D1’ * D1; % quadratic part of the scatter matrix
                temp = D1.Transpose() * D1;
                for (int xx = 0; xx < 3; xx++)
                {
                    for (int yy = 0; yy < 3; yy++)
                    {
                        S1[xx, yy] = temp[xx, yy];
                    }
                }

                //5 S2 = D1’ * D2; % combined part of the scatter matrix
                temp = D1.Transpose() * D2;
                for (int xx = 0; xx < 3; xx++)
                {
                    for (int yy = 0; yy < 3; yy++)
                    {
                        S2[xx, yy] = temp[xx, yy];
                    }
                }

                //6 S3 = D2’ * D2; % linear part of the scatter matrix
                temp = D2.Transpose() * D2;
                for (int xx = 0; xx < 3; xx++)
                {
                    for (int yy = 0; yy < 3; yy++)
                    {
                        S3[xx, yy] = temp[xx, yy];
                    }
                }

                //7 T = - inv(S3) * S2’; % for getting a2 from a1
                if (Determinant(S3) > 0)
                {
                    T = -1 * S3.Inverse() * S2.Transpose();

                    //8 M = S1 + S2 * T; % reduced scatter matrix
                    M = S1 + S2 * T;

                    //9 M = [M(3, :) ./ 2; - M(2, :); M(1, :) ./ 2]; % premultiply by inv(C1)
                    M = C1 * M;

                    //10 [evec, eval] = eig(M); % solve eigensystem
                    ComplexEigensystem eigenSystem = M.Eigensystem();

                    //11 cond = 4 * evec(1, :) .* evec(3, :) - evec(2, :) .ˆ 2; % evaluate a’Ca
                    //12 a1 = evec(:, find(cond > 0)); % eigenvector for min. pos. eigenvalue
                    for (int xx = 0; xx < eigenSystem.Dimension; xx++)
                    {
                        Vector <Complex> vector    = eigenSystem.Eigenvector(xx);
                        Complex          condition = 4 * vector[0] * vector[2] - vector[1] * vector[1];
                        if (condition.Im == 0 && condition.Re > 0)
                        {
                            // Solution is found
                            for (int yy = 0; yy < vector.Count(); yy++)
                            {
                                a1[yy, 0] = vector[yy].Re;
                            }
                        }
                    }

                    //13 a2 = T * a1; % ellipse coefficients
                    a2 = T * a1;

                    //14 a = [a1; a2]; % ellipse coefficients
                    par[0] = a1[0, 0];
                    par[1] = a1[1, 0];
                    par[2] = a1[2, 0];
                    par[3] = a2[0, 0];
                    par[4] = a2[1, 0];
                    par[5] = a2[2, 0];
                }
            }

            for (int i = 0; i < par.Count(); i++)
            {
                if (!double.IsNaN(par[i]) && !double.IsInfinity(par[i]))
                {
                    Parameters[i] = par[i];
                }
                else
                {
                    Parameters[i] = 0;
                }
            }
        }
Exemple #51
0
 protected abstract SquareMatrix <T> Visit(DiagonalMatrix <T> lhs, SquareMatrix <T> rhs);
Exemple #52
0
 protected abstract SquareMatrix <T> Visit(SymmetricalMatrix <T> lhs, SquareMatrix <T> rhs);
Exemple #53
0
        public void EnsureSizeGuardCase2Test()
        {
            SquareMatrix <int> matrix = new SquareMatrix <int>(256);

            matrix.EnsureSize(0);
        }
 public OSquareMatrix ExpectationDifferential(IManifoldPoint point, double time)
 {
     return(SquareMatrix.Scalar(StateSpace.Dimension, Math.Exp(-time / RelaxationTime)));
 }
Exemple #55
0
 public abstract Vector FindSolution(SquareMatrix inputMatrix, Vector inputElements);
Exemple #56
0
 protected sealed override OSquareMatrix FiberDifferential(State state, IManifoldPoint basePoint2, double time)
 {
     return(SquareMatrix.Id(Fiber.Dimension));
 }
Exemple #57
0
 /// <summary>
 /// Initials the new decorator.
 /// </summary>
 /// <param name="squareMatrix"></param>
 public MatrixDecorator(SquareMatrix <T> squareMatrix)
 {
     this.squareMatrix = squareMatrix ?? throw new ArgumentNullException(nameof(squareMatrix));
 }
Exemple #58
0
        public void Sum_RightMatrixIsNull_TrowArgumentNullException()
        {
            SquareMatrix <int> matr = new SquareMatrix <int>(2, new int[] { 1 });

            NUnit.Framework.Assert.Throws <ArgumentNullException>(() => MatrixOperation.Sum <int>(matr, null));
        }
Exemple #59
0
        public void MatrixTest_CreateSquare()
        {
            var matrix = new SquareMatrix <int>(this.squareArray);

            this.ShowMatrix(matrix);
        }
 public void MatrixShouldThrowExceptionWhenNegativeSizePassed()
 {
     var matrix = new SquareMatrix(-5);
 }