Example #1
0
 public GeneralMatrix CalculateHessian(double[]x)
 {
     GeneralMatrix hessian = new GeneralMatrix(Dimension,Dimension);
     for (int i=0; i<Dimension; i++)
         for (int j=0; j<Dimension; j++)
             hessian.SetElement(i,j,GetPartialDerivativeVal(i,j,x));
     return hessian;
 }
Example #2
0
 public void LUDecomposition()
 {
     GeneralMatrix A = new GeneralMatrix(columnwise, 4);
     int n = A.ColumnDimension;
     A = A.GetMatrix(0, n - 1, 0, n - 1);
     A.SetElement(0, 0, 0.0);
     LUDecomposition LU = A.LUD();
     Assert.IsTrue(GeneralTests.Check(A.GetMatrix(LU.Pivot, 0, n - 1), LU.L.Multiply(LU.U)));
 }
Example #3
0
        public static void Main(System.String[] argv)
        {
            GeneralMatrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL;
            int errorCount = 0;
            int warningCount = 0;
            double tmp;
            double[] columnwise = new double[]{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0};
            double[] rowwise = new double[]{1.0, 4.0, 7.0, 10.0, 2.0, 5.0, 8.0, 11.0, 3.0, 6.0, 9.0, 12.0};
            double[][] avals = {new double[]{1.0, 4.0, 7.0, 10.0}, new double[]{2.0, 5.0, 8.0, 11.0}, new double[]{3.0, 6.0, 9.0, 12.0}};
            double[][] rankdef = avals;
            double[][] tvals = {new double[]{1.0, 2.0, 3.0}, new double[]{4.0, 5.0, 6.0}, new double[]{7.0, 8.0, 9.0}, new double[]{10.0, 11.0, 12.0}};
            double[][] subavals = {new double[]{5.0, 8.0, 11.0}, new double[]{6.0, 9.0, 12.0}};
            double[][] rvals = {new double[]{1.0, 4.0, 7.0}, new double[]{2.0, 5.0, 8.0, 11.0}, new double[]{3.0, 6.0, 9.0, 12.0}};
            double[][] pvals = {new double[]{1.0, 1.0, 1.0}, new double[]{1.0, 2.0, 3.0}, new double[]{1.0, 3.0, 6.0}};
            double[][] ivals = {new double[]{1.0, 0.0, 0.0, 0.0}, new double[]{0.0, 1.0, 0.0, 0.0}, new double[]{0.0, 0.0, 1.0, 0.0}};
            double[][] evals = {new double[]{0.0, 1.0, 0.0, 0.0}, new double[]{1.0, 0.0, 2e-7, 0.0}, new double[]{0.0, - 2e-7, 0.0, 1.0}, new double[]{0.0, 0.0, 1.0, 0.0}};
            double[][] square = {new double[]{166.0, 188.0, 210.0}, new double[]{188.0, 214.0, 240.0}, new double[]{210.0, 240.0, 270.0}};
            double[][] sqSolution = {new double[]{13.0}, new double[]{15.0}};
            double[][] condmat = {new double[]{1.0, 3.0}, new double[]{7.0, 9.0}};
            int rows = 3, cols = 4;
            int invalidld = 5; /* should trigger bad shape for construction with val */
            int raggedr = 0; /* (raggedr,raggedc) should be out of bounds in ragged array */
            int raggedc = 4;
            int validld = 3; /* leading dimension of intended test Matrices */
            int nonconformld = 4; /* leading dimension which is valid, but nonconforming */
            int ib = 1, ie = 2, jb = 1, je = 3; /* index ranges for sub GeneralMatrix */
            int[] rowindexset = new int[]{1, 2};
            int[] badrowindexset = new int[]{1, 3};
            int[] columnindexset = new int[]{1, 2, 3};
            int[] badcolumnindexset = new int[]{1, 2, 4};
            double columnsummax = 33.0;
            double rowsummax = 30.0;
            double sumofdiagonals = 15;
            double sumofsquares = 650;

            /// <summary>Constructors and constructor-like methods:
            /// double[], int
            /// double[][]
            /// int, int
            /// int, int, double
            /// int, int, double[][]
            /// Create(double[][])
            /// Random(int,int)
            /// Identity(int)
            ///
            /// </summary>

            print("\nTesting constructors and constructor-like methods...\n");
            try
            {
                /// <summary>check that exception is thrown in packed constructor with invalid length *</summary>
                A = new GeneralMatrix(columnwise, invalidld);
                errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input");
            }
            catch (System.ArgumentException e)
            {
                try_success("Catch invalid length in packed constructor... ", e.Message);
            }
            try
            {
                /// <summary>check that exception is thrown in default constructor
                /// if input array is 'ragged' *
                /// </summary>
                A = new GeneralMatrix(rvals);
                tmp = A.GetElement(raggedr, raggedc);
            }
            catch (System.ArgumentException e)
            {
                try_success("Catch ragged input to default constructor... ", e.Message);
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                /// <summary>check that exception is thrown in Create
                /// if input array is 'ragged' *
                /// </summary>
                A = GeneralMatrix.Create(rvals);
                tmp = A.GetElement(raggedr, raggedc);
            }
            catch (System.ArgumentException e)
            {
                try_success("Catch ragged input to Create... ", e.Message);
                System.Console.Out.WriteLine(e.Message);
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "Catch ragged input to Create... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later");
                System.Console.Out.WriteLine(e.Message);
            }

            A = new GeneralMatrix(columnwise, validld);
            B = new GeneralMatrix(avals);
            tmp = B.GetElement(0, 0);
            avals[0][0] = 0.0;
            C = B.Subtract(A);
            avals[0][0] = tmp;
            B = GeneralMatrix.Create(avals);
            tmp = B.GetElement(0, 0);
            avals[0][0] = 0.0;
            if ((tmp - B.GetElement(0, 0)) != 0.0)
            {
                /// <summary>check that Create behaves properly *</summary>
                errorCount = try_failure(errorCount, "Create... ", "Copy not effected... data visible outside");
            }
            else
            {
                try_success("Create... ", "");
            }
            avals[0][0] = columnwise[0];
            I = new GeneralMatrix(ivals);
            try
            {
                check(I, GeneralMatrix.Identity(3, 4));
                try_success("Identity... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Identity... ", "Identity GeneralMatrix not successfully created");
                System.Console.Out.WriteLine(e.Message);
            }

            /// <summary>Access Methods:
            /// getColumnDimension()
            /// getRowDimension()
            /// getArray()
            /// getArrayCopy()
            /// getColumnPackedCopy()
            /// getRowPackedCopy()
            /// get(int,int)
            /// GetMatrix(int,int,int,int)
            /// GetMatrix(int,int,int[])
            /// GetMatrix(int[],int,int)
            /// GetMatrix(int[],int[])
            /// set(int,int,double)
            /// SetMatrix(int,int,int,int,GeneralMatrix)
            /// SetMatrix(int,int,int[],GeneralMatrix)
            /// SetMatrix(int[],int,int,GeneralMatrix)
            /// SetMatrix(int[],int[],GeneralMatrix)
            ///
            /// </summary>

            print("\nTesting access methods...\n");

            /// <summary>Various get methods:
            ///
            /// </summary>

            B = new GeneralMatrix(avals);
            if (B.RowDimension != rows)
            {
                errorCount = try_failure(errorCount, "getRowDimension... ", "");
            }
            else
            {
                try_success("getRowDimension... ", "");
            }
            if (B.ColumnDimension != cols)
            {
                errorCount = try_failure(errorCount, "getColumnDimension... ", "");
            }
            else
            {
                try_success("getColumnDimension... ", "");
            }
            B = new GeneralMatrix(avals);
            double[][] barray = B.Array;
            if (barray != avals)
            {
                errorCount = try_failure(errorCount, "getArray... ", "");
            }
            else
            {
                try_success("getArray... ", "");
            }
            barray = B.ArrayCopy;
            if (barray == avals)
            {
                errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied");
            }
            try
            {
                check(barray, avals);
                try_success("getArrayCopy... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied");
                System.Console.Out.WriteLine(e.Message);
            }
            double[] bpacked = B.ColumnPackedCopy;
            try
            {
                check(bpacked, columnwise);
                try_success("getColumnPackedCopy... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns");
                System.Console.Out.WriteLine(e.Message);
            }
            bpacked = B.RowPackedCopy;
            try
            {
                check(bpacked, rowwise);
                try_success("getRowPackedCopy... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                tmp = B.GetElement(B.RowDimension, B.ColumnDimension - 1);
                errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    tmp = B.GetElement(B.RowDimension - 1, B.ColumnDimension);
                    errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("get(int,int)... OutofBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                if (B.GetElement(B.RowDimension - 1, B.ColumnDimension - 1) != avals[B.RowDimension - 1][B.ColumnDimension - 1])
                {
                    errorCount = try_failure(errorCount, "get(int,int)... ", "GeneralMatrix entry (i,j) not successfully retreived");
                }
                else
                {
                    try_success("get(int,int)... ", "");
                }
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e.Message);
            }
            SUB = new GeneralMatrix(subavals);
            try
            {
                M = B.GetMatrix(ib, ie + B.RowDimension + 1, jb, je);
                errorCount = try_failure(errorCount, "GetMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    M = B.GetMatrix(ib, ie, jb, je + B.ColumnDimension + 1);
                    errorCount = try_failure(errorCount, "GetMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("GetMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                M = B.GetMatrix(ib, ie, jb, je);
                try
                {
                    check(SUB, M);
                    try_success("GetMatrix(int,int,int,int)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "GetMatrix(int,int,int,int)... ", "submatrix not successfully retreived");
                    System.Console.Out.WriteLine(e.Message);
                }
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e.Message);
            }

            try
            {
                M = B.GetMatrix(ib, ie, badcolumnindexset);
                errorCount = try_failure(errorCount, "GetMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    M = B.GetMatrix(ib, ie + B.RowDimension + 1, columnindexset);
                    errorCount = try_failure(errorCount, "GetMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("GetMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                M = B.GetMatrix(ib, ie, columnindexset);
                try
                {
                    check(SUB, M);
                    try_success("GetMatrix(int,int,int[])... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "GetMatrix(int,int,int[])... ", "submatrix not successfully retreived");
                    System.Console.Out.WriteLine(e.Message);
                }
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                M = B.GetMatrix(badrowindexset, jb, je);
                errorCount = try_failure(errorCount, "GetMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    M = B.GetMatrix(rowindexset, jb, je + B.ColumnDimension + 1);
                    errorCount = try_failure(errorCount, "GetMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("GetMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                M = B.GetMatrix(rowindexset, jb, je);
                try
                {
                    check(SUB, M);
                    try_success("GetMatrix(int[],int,int)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "GetMatrix(int[],int,int)... ", "submatrix not successfully retreived");
                    System.Console.Out.WriteLine(e.Message);
                }
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                M = B.GetMatrix(badrowindexset, columnindexset);
                errorCount = try_failure(errorCount, "GetMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    M = B.GetMatrix(rowindexset, badcolumnindexset);
                    errorCount = try_failure(errorCount, "GetMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("GetMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                M = B.GetMatrix(rowindexset, columnindexset);
                try
                {
                    check(SUB, M);
                    try_success("GetMatrix(int[],int[])... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "GetMatrix(int[],int[])... ", "submatrix not successfully retreived");
                    System.Console.Out.WriteLine(e.Message);
                }
            }
            catch (System.IndexOutOfRangeException e)
            {
                errorCount = try_failure(errorCount, "GetMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e.Message);
            }

            /// <summary>Various set methods:
            ///
            /// </summary>

            try
            {
                B.SetElement(B.RowDimension, B.ColumnDimension - 1, 0.0);
                errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    B.SetElement(B.RowDimension - 1, B.ColumnDimension, 0.0);
                    errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("set(int,int,double)... OutofBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetElement(ib, jb, 0.0);
                tmp = B.GetElement(ib, jb);
                try
                {
                    check(tmp, 0.0);
                    try_success("set(int,int,double)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "set(int,int,double)... ", "GeneralMatrix element not successfully set");
                    System.Console.Out.WriteLine(e.Message);
                }
            }
            catch (System.IndexOutOfRangeException e1)
            {
                errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e1.Message);
            }
            M = new GeneralMatrix(2, 3, 0.0);
            try
            {
                B.SetMatrix(ib, ie + B.RowDimension + 1, jb, je, M);
                errorCount = try_failure(errorCount, "SetMatrix(int,int,int,int,GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    B.SetMatrix(ib, ie, jb, je + B.ColumnDimension + 1, M);
                    errorCount = try_failure(errorCount, "SetMatrix(int,int,int,int,GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("SetMatrix(int,int,int,int,GeneralMatrix)... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int,int,int,int,GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(ib, ie, jb, je, M);
                try
                {
                    check(M.Subtract(B.GetMatrix(ib, ie, jb, je)), M);
                    try_success("SetMatrix(int,int,int,int,GeneralMatrix)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "SetMatrix(int,int,int,int,GeneralMatrix)... ", "submatrix not successfully set");
                    System.Console.Out.WriteLine(e.Message);
                }
                B.SetMatrix(ib, ie, jb, je, SUB);
            }
            catch (System.IndexOutOfRangeException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int,int,int,int,GeneralMatrix)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(ib, ie + B.RowDimension + 1, columnindexset, M);
                errorCount = try_failure(errorCount, "SetMatrix(int,int,int[],GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    B.SetMatrix(ib, ie, badcolumnindexset, M);
                    errorCount = try_failure(errorCount, "SetMatrix(int,int,int[],GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("SetMatrix(int,int,int[],GeneralMatrix)... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int,int,int[],GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(ib, ie, columnindexset, M);
                try
                {
                    check(M.Subtract(B.GetMatrix(ib, ie, columnindexset)), M);
                    try_success("SetMatrix(int,int,int[],GeneralMatrix)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "SetMatrix(int,int,int[],GeneralMatrix)... ", "submatrix not successfully set");
                    System.Console.Out.WriteLine(e.Message);
                }
                B.SetMatrix(ib, ie, jb, je, SUB);
            }
            catch (System.IndexOutOfRangeException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int,int,int[],GeneralMatrix)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(rowindexset, jb, je + B.ColumnDimension + 1, M);
                errorCount = try_failure(errorCount, "SetMatrix(int[],int,int,GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    B.SetMatrix(badrowindexset, jb, je, M);
                    errorCount = try_failure(errorCount, "SetMatrix(int[],int,int,GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("SetMatrix(int[],int,int,GeneralMatrix)... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int[],int,int,GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(rowindexset, jb, je, M);
                try
                {
                    check(M.Subtract(B.GetMatrix(rowindexset, jb, je)), M);
                    try_success("SetMatrix(int[],int,int,GeneralMatrix)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "SetMatrix(int[],int,int,GeneralMatrix)... ", "submatrix not successfully set");
                    System.Console.Out.WriteLine(e.Message);
                }
                B.SetMatrix(ib, ie, jb, je, SUB);
            }
            catch (System.IndexOutOfRangeException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int[],int,int,GeneralMatrix)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(rowindexset, badcolumnindexset, M);
                errorCount = try_failure(errorCount, "SetMatrix(int[],int[],GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
            }
            catch (System.IndexOutOfRangeException e)
            {
                System.Console.Out.WriteLine(e.Message);
                try
                {
                    B.SetMatrix(badrowindexset, columnindexset, M);
                    errorCount = try_failure(errorCount, "SetMatrix(int[],int[],GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                }
                catch (System.IndexOutOfRangeException e1)
                {
                    try_success("SetMatrix(int[],int[],GeneralMatrix)... ArrayIndexOutOfBoundsException... ", "");
                    System.Console.Out.WriteLine(e1.Message);
                }
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int[],int[],GeneralMatrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown");
                System.Console.Out.WriteLine(e1.Message);
            }
            try
            {
                B.SetMatrix(rowindexset, columnindexset, M);
                try
                {
                    check(M.Subtract(B.GetMatrix(rowindexset, columnindexset)), M);
                    try_success("SetMatrix(int[],int[],GeneralMatrix)... ", "");
                }
                catch (System.SystemException e)
                {
                    errorCount = try_failure(errorCount, "SetMatrix(int[],int[],GeneralMatrix)... ", "submatrix not successfully set");
                    System.Console.Out.WriteLine(e.Message);
                }
            }
            catch (System.IndexOutOfRangeException e1)
            {
                errorCount = try_failure(errorCount, "SetMatrix(int[],int[],GeneralMatrix)... ", "Unexpected ArrayIndexOutOfBoundsException");
                System.Console.Out.WriteLine(e1.Message);
            }

            /// <summary>Array-like methods:
            /// Subtract
            /// SubtractEquals
            /// Add
            /// AddEquals
            /// ArrayLeftDivide
            /// ArrayLeftDivideEquals
            /// ArrayRightDivide
            /// ArrayRightDivideEquals
            /// arrayTimes
            /// ArrayMultiplyEquals
            /// uminus
            ///
            /// </summary>

            print("\nTesting array-like methods...\n");
            S = new GeneralMatrix(columnwise, nonconformld);
            R = GeneralMatrix.Random(A.RowDimension, A.ColumnDimension);
            A = R;
            try
            {
                S = A.Subtract(S);
                errorCount = try_failure(errorCount, "Subtract conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("Subtract conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            if (A.Subtract(R).Norm1() != 0.0)
            {
                errorCount = try_failure(errorCount, "Subtract... ", "(difference of identical Matrices is nonzero,\nSubsequent use of Subtract should be suspect)");
            }
            else
            {
                try_success("Subtract... ", "");
            }
            A = R.Copy();
            A.SubtractEquals(R);
            Z = new GeneralMatrix(A.RowDimension, A.ColumnDimension);
            try
            {
                A.SubtractEquals(S);
                errorCount = try_failure(errorCount, "SubtractEquals conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("SubtractEquals conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            if (A.Subtract(Z).Norm1() != 0.0)
            {
                errorCount = try_failure(errorCount, "SubtractEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of Subtract should be suspect)");
            }
            else
            {
                try_success("SubtractEquals... ", "");
            }

            A = R.Copy();
            B = GeneralMatrix.Random(A.RowDimension, A.ColumnDimension);
            C = A.Subtract(B);
            try
            {
                S = A.Add(S);
                errorCount = try_failure(errorCount, "Add conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("Add conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(C.Add(B), A);
                try_success("Add... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Add... ", "(C = A - B, but C + B != A)");
                System.Console.Out.WriteLine(e.Message);
            }
            C = A.Subtract(B);
            C.AddEquals(B);
            try
            {
                A.AddEquals(S);
                errorCount = try_failure(errorCount, "AddEquals conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("AddEquals conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(C, A);
                try_success("AddEquals... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "AddEquals... ", "(C = A - B, but C = C + B != A)");
                System.Console.Out.WriteLine(e.Message);
            }
            A = R.UnaryMinus();
            try
            {
                check(A.Add(R), Z);
                try_success("UnaryMinus... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)");
                System.Console.Out.WriteLine(e.Message);
            }
            A = R.Copy();
            O = new GeneralMatrix(A.RowDimension, A.ColumnDimension, 1.0);
            C = A.ArrayLeftDivide(R);
            try
            {
                S = A.ArrayLeftDivide(S);
                errorCount = try_failure(errorCount, "ArrayLeftDivide conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("ArrayLeftDivide conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(C, O);
                try_success("ArrayLeftDivide... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "ArrayLeftDivide... ", "(M.\\M != ones)");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                A.ArrayLeftDivideEquals(S);
                errorCount = try_failure(errorCount, "ArrayLeftDivideEquals conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("ArrayLeftDivideEquals conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            A.ArrayLeftDivideEquals(R);
            try
            {
                check(A, O);
                try_success("ArrayLeftDivideEquals... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "ArrayLeftDivideEquals... ", "(M.\\M != ones)");
                System.Console.Out.WriteLine(e.Message);
            }
            A = R.Copy();
            try
            {
                A.ArrayRightDivide(S);
                errorCount = try_failure(errorCount, "ArrayRightDivide conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("ArrayRightDivide conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            C = A.ArrayRightDivide(R);
            try
            {
                check(C, O);
                try_success("ArrayRightDivide... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "ArrayRightDivide... ", "(M./M != ones)");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                A.ArrayRightDivideEquals(S);
                errorCount = try_failure(errorCount, "ArrayRightDivideEquals conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("ArrayRightDivideEquals conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            A.ArrayRightDivideEquals(R);
            try
            {
                check(A, O);
                try_success("ArrayRightDivideEquals... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "ArrayRightDivideEquals... ", "(M./M != ones)");
                System.Console.Out.WriteLine(e.Message);
            }
            A = R.Copy();
            B = GeneralMatrix.Random(A.RowDimension, A.ColumnDimension);
            try
            {
                S = A.ArrayMultiply(S);
                errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("arrayTimes conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            C = A.ArrayMultiply(B);
            try
            {
                check(C.ArrayRightDivideEquals(B), A);
                try_success("arrayTimes... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                A.ArrayMultiplyEquals(S);
                errorCount = try_failure(errorCount, "ArrayMultiplyEquals conformance check... ", "nonconformance not raised");
            }
            catch (System.ArgumentException e)
            {
                try_success("ArrayMultiplyEquals conformance check... ", "");
                System.Console.Out.WriteLine(e.Message);
            }
            A.ArrayMultiplyEquals(B);
            try
            {
                check(A.ArrayRightDivideEquals(B), R);
                try_success("ArrayMultiplyEquals... ", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "ArrayMultiplyEquals... ", "(A = R, A = A.*B, but A./B != R)");
                System.Console.Out.WriteLine(e.Message);
            }

            /// <summary>LA methods:
            /// Transpose
            /// Multiply
            /// Condition
            /// Rank
            /// Determinant
            /// trace
            /// Norm1
            /// norm2
            /// normF
            /// normInf
            /// Solve
            /// solveTranspose
            /// Inverse
            /// chol
            /// Eigen
            /// lu
            /// qr
            /// svd
            ///
            /// </summary>

            print("\nTesting linear algebra methods...\n");
            A = new GeneralMatrix(columnwise, 3);
            T = new GeneralMatrix(tvals);
            T = A.Transpose();
            try
            {
                check(A.Transpose(), T);
                try_success("Transpose...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Transpose()...", "Transpose unsuccessful");
                System.Console.Out.WriteLine(e.Message);
            }
            A.Transpose();
            try
            {
                check(A.Norm1(), columnsummax);
                try_success("Norm1...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Norm1()...", "incorrect norm calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(A.NormInf(), rowsummax);
                try_success("normInf()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(A.NormF(), System.Math.Sqrt(sumofsquares));
                try_success("normF...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(A.Trace(), sumofdiagonals);
                try_success("trace()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(A.GetMatrix(0, A.RowDimension - 1, 0, A.RowDimension - 1).Determinant(), 0.0);
                try_success("Determinant()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Determinant()...", "incorrect determinant calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            SQ = new GeneralMatrix(square);
            try
            {
                check(A.Multiply(A.Transpose()), SQ);
                try_success("Multiply(GeneralMatrix)...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Multiply(GeneralMatrix)...", "incorrect GeneralMatrix-GeneralMatrix product calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            try
            {
                check(A.Multiply(0.0), Z);
                try_success("Multiply(double)...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Multiply(double)...", "incorrect GeneralMatrix-scalar product calculation");
                System.Console.Out.WriteLine(e.Message);
            }

            A = new GeneralMatrix(columnwise, 4);
            QRDecomposition QR = A.QRD();
            R = QR.R;
            try
            {
                check(A, QR.Q.Multiply(R));
                try_success("QRDecomposition...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            SingularValueDecomposition SVD = A.SVD();
            try
            {
                check(A, SVD.GetU().Multiply(SVD.S.Multiply(SVD.GetV().Transpose())));
                try_success("SingularValueDecomposition...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            DEF = new GeneralMatrix(rankdef);
            try
            {
                check(DEF.Rank(), System.Math.Min(DEF.RowDimension, DEF.ColumnDimension) - 1);
                try_success("Rank()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Rank()...", "incorrect Rank calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            B = new GeneralMatrix(condmat);
            SVD = B.SVD();
            double[] singularvalues = SVD.SingularValues;
            try
            {
                check(B.Condition(), singularvalues[0] / singularvalues[System.Math.Min(B.RowDimension, B.ColumnDimension) - 1]);
                try_success("Condition()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Condition()...", "incorrect condition number calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            int n = A.ColumnDimension;
            A = A.GetMatrix(0, n - 1, 0, n - 1);
            A.SetElement(0, 0, 0.0);
            LUDecomposition LU = A.LUD();
            try
            {
                check(A.GetMatrix(LU.Pivot, 0, n - 1), LU.L.Multiply(LU.U));
                try_success("LUDecomposition...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            X = A.Inverse();
            try
            {
                check(A.Multiply(X), GeneralMatrix.Identity(3, 3));
                try_success("Inverse()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Inverse()...", "incorrect Inverse calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            O = new GeneralMatrix(SUB.RowDimension, 1, 1.0);
            SOL = new GeneralMatrix(sqSolution);
            SQ = SUB.GetMatrix(0, SUB.RowDimension - 1, 0, SUB.RowDimension - 1);
            try
            {
                check(SQ.Solve(SOL), O);
                try_success("Solve()...", "");
            }
            catch (System.ArgumentException e1)
            {
                errorCount = try_failure(errorCount, "Solve()...", e1.Message);
                System.Console.Out.WriteLine(e1.Message);
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "Solve()...", e.Message);
                System.Console.Out.WriteLine(e.Message);
            }
            A = new GeneralMatrix(pvals);
            CholeskyDecomposition Chol = A.chol();
            GeneralMatrix L = Chol.GetL();
            try
            {
                check(A, L.Multiply(L.Transpose()));
                try_success("CholeskyDecomposition...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            X = Chol.Solve(GeneralMatrix.Identity(3, 3));
            try
            {
                check(A.Multiply(X), GeneralMatrix.Identity(3, 3));
                try_success("CholeskyDecomposition Solve()...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "CholeskyDecomposition Solve()...", "incorrect Choleskydecomposition Solve calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            EigenvalueDecomposition Eig = A.Eigen();
            GeneralMatrix D = Eig.D;
            GeneralMatrix V = Eig.GetV();
            try
            {
                check(A.Multiply(V), V.Multiply(D));
                try_success("EigenvalueDecomposition (symmetric)...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation");
                System.Console.Out.WriteLine(e.Message);
            }
            A = new GeneralMatrix(evals);
            Eig = A.Eigen();
            D = Eig.D;
            V = Eig.GetV();
            try
            {
                check(A.Multiply(V), V.Multiply(D));
                try_success("EigenvalueDecomposition (nonsymmetric)...", "");
            }
            catch (System.SystemException e)
            {
                errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation");
                System.Console.Out.WriteLine(e.Message);
            }

            print("\nTestMatrix completed.\n");
            print("Total errors reported: " + System.Convert.ToString(errorCount) + "\n");
            print("Total warnings reported: " + System.Convert.ToString(warningCount) + "\n");
        }
Example #4
0
        private void computeaccCalButton_Click(object sender, EventArgs e)
        {
            int i,j;

            calStatusText.Text = "Computing Calibration...";

            // Construct D matrix
            // D = [x.^2, y.^2, z.^2, x.*y, x.*z, y.*z, x, y, z, ones(N,1)];
            for (i = 0; i < SAMPLES; i++ )
            {
                // x^2 term
                D.SetElement(i,0, loggedData[i,0]*loggedData[i,0]);

                // y^2 term
                D.SetElement(i,1,loggedData[i,1]*loggedData[i,1]);

                // z^2 term
                D.SetElement(i, 2, loggedData[i, 2] * loggedData[i, 2]);

                // x*y term
                D.SetElement(i,3,loggedData[i,0]*loggedData[i,1]);

                // x*z term
                D.SetElement(i,4,loggedData[i,0]*loggedData[i,2]);

                // y*z term
                D.SetElement(i,5,loggedData[i,1]*loggedData[i,2]);

                // x term
                D.SetElement(i,6,loggedData[i,0]);

                // y term
                D.SetElement(i,7,loggedData[i,1]);

                // z term
                D.SetElement(i,8,loggedData[i,2]);

                // Constant term
                D.SetElement(i,9,1);
            }

            // QR=triu(qr(D))
            QRDecomposition QR = new QRDecomposition(D);
            // [U,S,V] = svd(D)
            SingularValueDecomposition SVD = new SingularValueDecomposition(QR.R);
            GeneralMatrix V = SVD.GetV();

            GeneralMatrix A = new GeneralMatrix(3, 3);

            double[] p = new double[V.RowDimension];

            for (i = 0; i < V.RowDimension; i++ )
            {
                p[i] = V.GetElement(i,V.ColumnDimension-1);
            }

            /*
            A = [p(1) p(4)/2 p(5)/2;
            p(4)/2 p(2) p(6)/2;
            p(5)/2 p(6)/2 p(3)];
             */

            if (p[0] < 0)
            {
                for (i = 0; i < V.RowDimension; i++)
                {
                    p[i] = -p[i];
                }
            }

            A.SetElement(0,0,p[0]);
            A.SetElement(0,1,p[3]/2);
            A.SetElement(1,2,p[4]/2);

            A.SetElement(1,0,p[3]/2);
            A.SetElement(1,1,p[1]);
            A.SetElement(1,2,p[5]/2);

            A.SetElement(2,0,p[4]/2);
            A.SetElement(2,1,p[5]/2);
            A.SetElement(2,2,p[2]);

            CholeskyDecomposition Chol = new CholeskyDecomposition(A);
            GeneralMatrix Ut = Chol.GetL();
            GeneralMatrix U = Ut.Transpose();

            double[] bvect = {p[6]/2,p[7]/2,p[8]/2};
            double d = p[9];
            GeneralMatrix b = new GeneralMatrix(bvect,3);

            GeneralMatrix v = Ut.Solve(b);

            double vnorm_sqrd = v.GetElement(0,0)*v.GetElement(0,0) + v.GetElement(1,0)*v.GetElement(1,0) + v.GetElement(2,0)*v.GetElement(2,0);
            double s = 1/Math.Sqrt(vnorm_sqrd - d);

            GeneralMatrix c = U.Solve(v);
            for (i = 0; i < 3; i++)
            {
                c.SetElement(i, 0, -c.GetElement(i, 0));
            }

            U = U.Multiply(s);

            for (i = 0; i < 3; i++)
            {
                for (j = 0; j < 3; j++)
                {
                    calMat[i, j] = U.GetElement(i, j);
                }
            }

            for (i = 0; i < 3; i++)
            {
                bias[i] = c.GetElement(i, 0);
            }

            accAlignment00.Text = calMat[0, 0].ToString();
            accAlignment01.Text = calMat[0, 1].ToString();
            accAlignment02.Text = calMat[0, 2].ToString();

            accAlignment10.Text = calMat[1, 0].ToString();
            accAlignment11.Text = calMat[1, 1].ToString();
            accAlignment12.Text = calMat[1, 2].ToString();

            accAlignment20.Text = calMat[2, 0].ToString();
            accAlignment21.Text = calMat[2, 1].ToString();
            accAlignment22.Text = calMat[2, 2].ToString();

            biasX.Text = bias[0].ToString();
            biasY.Text = bias[1].ToString();
            biasZ.Text = bias[2].ToString();

            calStatusText.Text = "Done";
            flashCommitButton.Enabled = true;
            accAlignmentCommitButton.Enabled = true;
        }
Example #5
0
        public void TestTranspose()
        {
            GeneralMatrix _gm = new GeneralMatrix(2,2);
            _gm.SetElement(0,0,1);
            _gm.SetElement(0,1,2);
            _gm.SetElement(1,0,3);
            _gm.SetElement(1,1,4);
            GeneralMatrix _ngm = _gm.Transpose();

            Assert.AreEqual(1,0,2);
        }
Example #6
0
        public void TestSolve()
        {
            GeneralMatrix _ls = new GeneralMatrix(2,2);
            _ls.SetElement(0,0,1);
            _ls.SetElement(0,1,2);
            _ls.SetElement(1,0,3);
            _ls.SetElement(1,1,4);

            GeneralMatrix _rs = new GeneralMatrix(2,1);
            _rs.SetElement(0,0,-3);
            _rs.SetElement(1,0,-5);

            GeneralMatrix _solution = _ls.Solve(_rs);

            Assert.AreEqual(_solution.GetElement(0,0),1);
            Assert.AreEqual(_solution.GetElement(1,0),-2);
        }
Example #7
0
        public void TestNorm1()
        {
            GeneralMatrix _gm = new GeneralMatrix(2,2);
            _gm.SetElement(0,0,1);
            _gm.SetElement(0,1,2);
            _gm.SetElement(1,0,3);
            _gm.SetElement(1,1,4);

            Assert.AreEqual(6,_gm.Norm1());
        }
Example #8
0
        /// <summary>
        /// Average values of the priority matrix over sum of columns.
        /// set values of sum of averaged rows into a new matrix
        /// </summary>
        /// <param name="argMatrix"></param>
        /// <param name="selection"></param>
        public void PCalc(GeneralMatrix argMatrix, GeneralMatrix selection)
        {
            int n = argMatrix.ColumnDimension;
            GeneralMatrix sMatrix = new GeneralMatrix(argMatrix.ArrayCopy);

            double c=0.0;
            int i,j;

            for (i=0;i<sMatrix.ColumnDimension; i++)
            {
                c=0.0;
                for (j=0; j<sMatrix.RowDimension; j++)
                    c+=sMatrix.GetElement(j,i);
                selection.SetElement(i,0,c);
            }

            for (i=0;i<sMatrix.ColumnDimension; i++)
            {
                for (j=0; j<sMatrix.RowDimension; j++)
                    sMatrix.SetElement(j,i,sMatrix.GetElement(j,i)/selection.GetElement(i,0));

            }

            for (i=0;i<sMatrix.RowDimension; i++)
            {
                c=0.0;
                for (j=0; j<sMatrix.ColumnDimension; j++)
                    c+=sMatrix.GetElement(i,j);
                selection.SetElement(i,0,c/n);
            }
        }
Example #9
0
        protected RpropResult RPropLoop(double[] seed, bool precise)
        {
            //Console.WriteLine("RpropLoop");
            InitialStepSize();

            double[] curGradient;

            RpropResult ret = new RpropResult();

            if (seed != null)
            {
                curGradient = InitialPointFromSeed(ret, seed);
            }
            else
            {
                curGradient = InitialPoint(ret);
            }
            double curUtil = ret.initialUtil;
            double oldUtil = curUtil;

            double[] formerGradient = new double[dim];
            double[] curValue       = new double[dim];
            double[] testValue      = new double[dim];
            double   lambda         = 0.1;

            Tuple <double[], double> tup;

            Buffer.BlockCopy(ret.initialValue, 0, curValue, 0, sizeof(double) * dim);


            formerGradient = curGradient;
            //Buffer.BlockCopy(curGradient,0,formerGradient,0,sizeof(double)*dim);


            int itcounter  = 0;
            int badcounter = 0;


            /*Console.WriteLine("Initial Sol:");
             * for(int i=0; i<dim;i++) {
             *      Console.Write("{0} ",curValue[i]);
             * }
             * Console.WriteLine();
             * Console.WriteLine("Initial Util: {0}",curUtil);
             */
#if (GSOLVER_LOG)
            Log(curUtil, curValue);
#endif

            int    maxIter = 60;
            int    maxBad  = 30;
            double minStep = 1E-11;
            if (precise)
            {
                maxIter = 120;                 //110
                maxBad  = 60;                  //60
                minStep = 1E-15;               //15
            }
            int convergendDims = 0;

            while (itcounter++ < maxIter && badcounter < maxBad)
            {
                convergendDims = 0;

                //First Order resp. approximated Second Order Gradient

                for (int i = 0; i < dim; i++)
                {
                    if (curGradient[i] * formerGradient[i] > 0)
                    {
                        rpropStepWidth[i] *= 1.3;
                    }
                    else if (curGradient[i] * formerGradient[i] < 0)
                    {
                        rpropStepWidth[i] *= 0.5;
                    }
                    rpropStepWidth[i] = Math.Max(minStep, rpropStepWidth[i]);
                    //rpropStepWidth[i] = Math.Max(0.000001,rpropStepWidth[i]);
                    if (curUtil > 0.0)
                    {
                        //if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i];
                        //else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i];
                    }
                    else
                    {
                        //linear assumption
                        //curValue[i] += -curUtil/curGradient[i];

                        //quadratic assumption

                        /*double ypSquare = 0;
                         * for(int j=0; j<dim; j++) {
                         *      ypSquare += curGradient[j]*curGradient[j];
                         * }
                         * double m=ypSquare/curUtil;
                         * curValue[i] = -curGradient[i]/(2*m) + curValue[i];*/
                    }

                    if (curValue[i] > limits[i, 1])
                    {
                        curValue[i] = limits[i, 1];
                    }
                    else if (curValue[i] < limits[i, 0])
                    {
                        curValue[i] = limits[i, 0];
                    }
                    if (rpropStepWidth[i] < rpropStepConvergenceThreshold[i])
                    {
                        ++convergendDims;
                    }
                }
                //Abort if all dimensions are converged
                if (!precise && convergendDims >= dim)
                {
                    if (curUtil > ret.finalUtil)
                    {
                        ret.finalUtil = curUtil;
                        Buffer.BlockCopy(curValue, 0, ret.finalValue, 0, sizeof(double) * dim);
                    }

                    return(ret);
                }
                // Conjugate Gradient
                if (curUtil < 0.5)
                {
                    DotNetMatrix.GeneralMatrix X = new DotNetMatrix.GeneralMatrix(dim * 2 + 1, dim);
                    DotNetMatrix.GeneralMatrix Y = new DotNetMatrix.GeneralMatrix(dim * 2 + 1, 1);
                    for (int n = 0; n < dim; n++)
                    {
                        X.SetElement(0, n, curValue[n]);
                    }
                    Y.SetElement(0, 0, 0);
                    for (int j = 0; j < dim * 2; j++)
                    {
                        for (int n = 0; n < dim; n++)
                        {
                            double rVal = rand.NextDouble() * rpropStepConvergenceThreshold[n] * 1000.0;
                            testValue[n] = curValue[n] + rVal;
                        }
                        tup = term.Differentiate(testValue);
                        for (int n = 0; n < dim; n++)
                        {
                            X.SetElement(j + 1, n, tup.Item1[n]);
                        }
                        Y.SetElement(j + 1, 0, tup.Item2 - curUtil);
                    }
                    DotNetMatrix.GeneralMatrix JJ = X.Transpose().Multiply(X);

                    /*if(curUtil>oldUtil) lambda *= 10;
                     * else lambda *= 0.1;*/
                    //DotNetMatrix.GeneralMatrix B = JJ.Add(GeneralMatrix.Identity(dim, dim).Multiply(lambda)).Inverse().Multiply(X.Transpose()).Multiply(Y);
                    DotNetMatrix.GeneralMatrix B = JJ.Add(JJ.SVD().S.Multiply(lambda)).Inverse().Multiply(X.Transpose()).Multiply(Y);
                    //DotNetMatrix.GeneralMatrix B = JJ.Inverse().Multiply(X.Transpose()).Multiply(Y);
                    for (int j = 0; j < dim; j++)
                    {
                        curValue[j] += 0.01 * B.GetElement(j, 0);
                    }
                    Console.WriteLine(curUtil);
                    Console.Write(B.Transpose());
                    Console.WriteLine();
                }
                /////////////////////////

                this.FEvals++;
                tup = term.Differentiate(curValue);
                bool allZero = true;
                for (int i = 0; i < dim; i++)
                {
                    if (Double.IsNaN(tup.Item1[i]))
                    {
                        ret.aborted = true;
#if (GSOLVER_LOG)
                        LogStep();
#endif
                        return(ret);
                    }
                    allZero &= (tup.Item1[i] == 0);
                }
                oldUtil        = curUtil;
                curUtil        = tup.Item2;
                formerGradient = curGradient;
                curGradient    = tup.Item1;
#if (GSOLVER_LOG)
                Log(curUtil, curValue);
#endif
                //Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil);

                if (curUtil > ret.finalUtil)
                {
                    badcounter = 0;                    //Math.Max(0,badcounter-1);

                    //if (curUtil-ret.finalUtil < 0.00000000000001) {
                    //Console.WriteLine("not better");
                    //	badcounter++;
                    //} else {
                    //badcounter = 0;
                    //}

                    ret.finalUtil = curUtil;
                    Buffer.BlockCopy(curValue, 0, ret.finalValue, 0, sizeof(double) * dim);
                    //ret.finalValue = curValue;
#if (ALWAYS_CHECK_THRESHOLD)
                    if (curUtil > utilityThreshold)
                    {
                        return(ret);
                    }
#endif
                }
                else
                {
                    //if (curUtil < ret.finalUtil || curUtil > 0) badcounter++;
                    badcounter++;
                }
                if (allZero)
                {
                    //Console.WriteLine("All Zero!");

                    /*Console.WriteLine("Util {0}",curUtil);
                     * Console.Write("Vals: ");
                     * for(int i=0; i < dim; i++) {
                     *      Console.Write("{0}\t",curValue[i]);
                     * }
                     * Console.WriteLine();*/
                    ret.aborted = false;
#if (GSOLVER_LOG)
                    LogStep();
#endif
                    return(ret);
                }
            }
#if (GSOLVER_LOG)
            LogStep();
#endif
            ret.aborted = false;
            return(ret);
        }
Example #10
0
 public void SetElementWithInvalidRowIndexThrowsAnException()
 {
     var matrix = new GeneralMatrix(avals);
     matrix.SetElement(matrix.RowDimension,matrix.ColumnDimension + 1, 0.0);
 }
Example #11
0
 public void SetElementCorrectlySetsAMatrixElement()
 {
     var matrix = new GeneralMatrix(avals);
     matrix.SetElement(ib,jb,0.0);
     Assert.AreEqual(0.0,matrix.GetElement(ib,jb));
 }
        private static GeneralMatrix makeDiagonalSquare(double[] m, int cols)
        {
            GeneralMatrix result = new GeneralMatrix(cols, cols);

            for (int j = 0; j < cols; j++)
            {
                for (int i = 0; i < cols; i++)
                {
                    if (j == i)
                    {
                        result.SetElement(i, j, m[i]);
                    }
                    else
                    {
                        result.SetElement(i, j, 0);
                    }
                }
            }
            return result;
        }
        private void GetFiles_Decompose_WriteToArff()
        {
            try {
                // sampleFactor is the amount to divide by the total size of the
                // data set
                // when determining the subsample that will be used in svd

                Console.WriteLine("Creating arff file...");
                DisplayMessage("Creating arff file...");

                // Create folder
                System.IO.Directory.CreateDirectory(OutputDir + "Results/");
                StreamWriter output = new StreamWriter(OutputDir + "Results/" + "resultsGalaxy.arff");

                output.Write("@relation 'galaxy'\n");
                output.Write("@attribute class real\n");
                output.Write("@attribute colorF real\n");
                output.Write("@attribute bulgeF real\n");
                output.Write("@attribute constF real\n");
                for (int i = 0; i < sv * 3; i++) {
                    output.Write("@attribute " + i + " real\n");
                }
                output.Write("@data\n");

                Console.WriteLine("Begin galaxy sampling");
                DisplayMessage("Begin galaxy sampling");

                // Initialize a three matrices that will hold all of the images
                // (r,g,b of each image where each row is an image)
                dataRed = new GeneralMatrix(galaxyData.Count() / sampleFactor,
                        imageScaleSize * imageScaleSize);
                dataGreen = new GeneralMatrix(galaxyData.Count() / sampleFactor,
                        imageScaleSize * imageScaleSize);
                dataBlue = new GeneralMatrix(galaxyData.Count() / sampleFactor,
                        imageScaleSize * imageScaleSize);

                // subsample from galaxydata
                System.Threading.Tasks.Parallel.For(0, galaxyData.Count() / sampleFactor, (int index) => {
                    Bitmap tempImage = getImage(OutputDir + "galaxies/"
                            + galaxyData[sampleFactor * index][0] + ".jpg", imageScaleSize);

                    for (int i = 0; i < imageScaleSize; i++) {
                        for (int j = 0; j < imageScaleSize; j++) {
                            int pixelColor = tempImage.GetPixel(i, j).ToArgb();
                            int[] rgb = new int[3];
                            rgb[0] += ((pixelColor & 0x00ff0000) >> 16);
                            rgb[1] += ((pixelColor & 0x0000ff00) >> 8);
                            rgb[2] += (pixelColor & 0x000000ff);

                            dataRed.SetElement(index, i * imageScaleSize + j, rgb[0]);
                            dataGreen.SetElement(index, i * imageScaleSize + j, rgb[1]);
                            dataBlue.SetElement(index, i * imageScaleSize + j, rgb[2]);
                        }
                    }

                    //if (index % 10 == 0)
                        //DisplayImage(index);
                    //Console.WriteLine("Galaxy " + (sampleFactor * index) + " finished");
                });

                Console.WriteLine("Galaxy sampling finished\nBegin R, G and B channel SVD");
                DisplayMessage("Galaxy sampling finished, Begin R, G and B channel SVD");

                // Perform svd on subsample:
                var redWorker = System.Threading.Tasks.Task.Factory.StartNew(() => svdR = new SingularValueDecomposition(dataRed));
                var greenWorker = System.Threading.Tasks.Task.Factory.StartNew(() => svdG = new SingularValueDecomposition(dataGreen));
                var blueWorker = System.Threading.Tasks.Task.Factory.StartNew(() => svdB = new SingularValueDecomposition(dataBlue));
                System.Threading.Tasks.Task.WaitAll(redWorker, greenWorker, blueWorker);

                // Create the basis for each component
                GeneralMatrix rV = svdR.GetV();
                Console.Write("dim rU: " + rV.RowDimension + ", "
                        + rV.ColumnDimension);
                GeneralMatrix gV = svdG.GetV();
                GeneralMatrix bV = svdB.GetV();

                rV = GetSVs(rV, sv);
                Console.Write("Svs: " + sv);
                Console.Write("Dim SsV: " + rV.RowDimension + ", "
                        + rV.ColumnDimension);
                gV = GetSVs(gV, sv);
                bV = GetSVs(bV, sv);

                // Perform the pseudoinverses
                frV = pinv(rV.Transpose());
                fgV = pinv(gV.Transpose());
                fbV = pinv(bV.Transpose());

                // Stores frV, fgV and fbV to file
                WriteToFile();

                Console.WriteLine("SVD finished");
                DisplayMessage("SVD finished, load full dataset for testing");

                Console.WriteLine("Begin filling dataset for testing");

                // fill the 'full' datasets
                dataRed = new GeneralMatrix(galaxyData.Count(), imageScaleSize
                        * imageScaleSize);
                dataGreen = new GeneralMatrix(galaxyData.Count(), imageScaleSize
                        * imageScaleSize);
                dataBlue = new GeneralMatrix(galaxyData.Count(), imageScaleSize
                        * imageScaleSize);

                System.Threading.Tasks.Parallel.For(0, galaxyData.Count(), (int index) => {
                    Bitmap tempImage = getImage(OutputDir + "galaxies/"
                            + galaxyData[index][0] + ".jpg", imageScaleSize);

                    for (int i = 0; i < imageScaleSize; i++) {
                        for (int j = 0; j < imageScaleSize; j++) {
                            int pixelColor = tempImage.GetPixel(i, j).ToArgb();
                            int[] rgb = new int[3];
                            rgb[0] += ((pixelColor & 0x00ff0000) >> 16);
                            rgb[1] += ((pixelColor & 0x0000ff00) >> 8);
                            rgb[2] += (pixelColor & 0x000000ff);

                            dataRed.SetElement(index, i * imageScaleSize + j, rgb[0]);
                            dataGreen.SetElement(index, i * imageScaleSize + j,
                                    rgb[1]);
                            dataBlue.SetElement(index, i * imageScaleSize + j, rgb[2]);
                        }
                    }

                });

                Console.WriteLine("Finished filling dataset for testing");
                DisplayMessage("Finished filling dataset for testing, begin projecting galaxies to U coordinate system");

                Console.WriteLine("Begin projecting galaxies to U coordinate system, writing to ARFF file");

                // Do the coordinate conversion
                rV = dataRed.Multiply(frV);
                gV = dataGreen.Multiply(fgV);
                bV = dataBlue.Multiply(fbV);

                Console.Write("Dim Final rU: " + rV.ColumnDimension
                        + ", " + rV.RowDimension);
                Console.WriteLine("galaxyData.Count(): " + galaxyData.Count());

                // write to the output file here:
                for (int imageIndex = 0; imageIndex < galaxyData.Count(); imageIndex++) {

                    Bitmap tempImage = getImage(OutputDir + "galaxies/"
                            + galaxyData[imageIndex][0] + ".jpg", imageScaleSize);

                    float colorFactor = (GetColor(tempImage)[0] / GetColor(tempImage)[2]);
                    float centralBulgeFactor = getCentralBulge(tempImage);
                    float consistencyFactor = GetConsistency(tempImage);

                    output.Write(galaxyData[imageIndex][1] + ", ");
                    output.Write(colorFactor + ", ");
                    output.Write(centralBulgeFactor + ", ");
                    output.Write(consistencyFactor + ", ");

                    // output data (r,g,b)
                    for (int i = 0; i < rV.ColumnDimension; i++) {
                        output.Write(rV.GetElement(imageIndex, i) + ", ");
                        output.Write(gV.GetElement(imageIndex, i) + ", ");
                        if (i == rV.ColumnDimension - 1) {
                            output.Write(bV.GetElement(imageIndex, i) + "\n");
                        }
                        else {
                            output.Write(bV.GetElement(imageIndex, i) + ", ");
                        }
                    }

                    //if (imageIndex % (galaxyData.Count() / 100) == 0)
                    //    DisplayImage(imageIndex);
                    DisplayMessage("Finished galaxy " + imageIndex.ToString() + " - " + (100 * imageIndex / galaxyData.Count()).ToString() + "%");

                }

                output.Flush();
                output.Close();
                output.Dispose();

                Console.Write("Finished creating arff file...");
                DisplayMessage("Finished creating arff file...");

            }
            catch (Exception ex) {
                Console.Write(ex.ToString());
            }
        }
        private void ClassifyGroup(string[] images, string filePath, StreamWriter output, int groupNum)
        {
            // fill the 'full' datasets
            dataRed = new GeneralMatrix(images.Count(), imageScaleSize
                    * imageScaleSize);
            dataGreen = new GeneralMatrix(images.Count(), imageScaleSize
                    * imageScaleSize);
            dataBlue = new GeneralMatrix(images.Count(), imageScaleSize
                    * imageScaleSize);

            //create the entire size of the dataset
            System.Threading.Tasks.Parallel.For(0, images.Count(), (int imageIndex) => {
                Bitmap tempImage = getImage(images[imageIndex], imageScaleSize);

                for (int i = 0; i < imageScaleSize; i++) {
                    for (int j = 0; j < imageScaleSize; j++) {
                        int pixelColor = tempImage.GetPixel(i, j).ToArgb();
                        int[] rgb = new int[3];
                        rgb[0] += ((pixelColor & 0x00ff0000) >> 16);
                        rgb[1] += ((pixelColor & 0x0000ff00) >> 8);
                        rgb[2] += (pixelColor & 0x000000ff);

                        dataRed.SetElement(imageIndex, i * imageScaleSize + j, rgb[0]);
                        dataGreen.SetElement(imageIndex, i * imageScaleSize + j,
                                rgb[1]);
                        dataBlue.SetElement(imageIndex, i * imageScaleSize + j, rgb[2]);
                    }
                }
                Console.WriteLine("SDSS Galaxy " + imageIndex + " put in main dataset");
            });

            //then convert the whole dataset to the same coordinate
            // Do the coordinate conversion
            GeneralMatrix rV = dataRed.Multiply(frV);
            GeneralMatrix gV = dataGreen.Multiply(fgV);
            GeneralMatrix bV = dataBlue.Multiply(fbV);

            Console.WriteLine("Dim Final rU: " + rV.ColumnDimension
                    + ", " + rV.RowDimension);
            Console.WriteLine("images.length: " + images.Count());

            // write to the output file here:
            for (int imageIndex = 0; imageIndex < images.Count(); imageIndex++) {

                Bitmap tempImage = getImage(images[imageIndex], imageScaleSize);

                float colorFactor = (GetColor(tempImage)[0] / GetColor(tempImage)[2]);
                float centralBulgeFactor = getCentralBulge(tempImage);
                float consistencyFactor = GetConsistency(tempImage);

                output.Write(-999 + ", ");

                output.Write(colorFactor + ", ");
                output.Write(centralBulgeFactor + ", ");
                output.Write(consistencyFactor + ", ");

                // output data (r,g,b)
                for (int i = 0; i < rV.ColumnDimension; i++) {
                    output.Write(rV.GetElement(imageIndex, i) + ", ");
                    output.Write(gV.GetElement(imageIndex, i) + ", ");
                    if (i == rV.ColumnDimension - 1) {
                        output.Write(bV.GetElement(imageIndex, i) + "\n");
                    }
                    else {
                        output.Write(bV.GetElement(imageIndex, i) + ", ");
                    }
                }

                Console.WriteLine("Creating ARFF classification file - " + (100 * imageIndex / images.Count()).ToString() + "%");
            }
        }
 // Take SV columns from the U matrix
 private static GeneralMatrix GetSVs(GeneralMatrix matrix, int sv)
 {
     GeneralMatrix toPass = new GeneralMatrix(matrix.RowDimension, sv);
     for (int j = 0; j < sv; j++) {
         for (int i = 0; i < matrix.RowDimension; i++) {
             toPass.SetElement(i, j, matrix.GetElement(i, j));
         }
     }
     return toPass;
 }
Example #16
0
        private double[][] calculateR()
        {
            sourceCount = sourceASTL.abstractLatticeGraph.VertexCount;
            targetCount = targetASTL.abstractLatticeGraph.VertexCount;

            GeneralMatrix newR = new GeneralMatrix(sourceCount * targetCount, 1);
            GeneralMatrix myA = new GeneralMatrix(A);

            //initial R
            for (int i = 0; i < newR.RowDimension; i++)
            {
                newR.SetElement(i, 0, 1.0 / newR.RowDimension);
            }

            //printMatrix(vector2Matrix(newR.Array, 0));

            //move similarity matrix to a double index vector
            GeneralMatrix newSim = new GeneralMatrix(sourceCount * targetCount, 1);

            for (int i = 0; i < sourceCount; i++)
                for (int j = 0; j < targetCount; j++)
                {
                    newSim.SetElement(targetCount * i + j, 0, simMatrix[i, j]);
                }

            //move structure similarity matrix to a double index vector
            GeneralMatrix newStructSim = new GeneralMatrix(sourceCount * targetCount, 1);

            //for (int i = 0; i < sourceCount; i++)
            //    for (int j = 0; j < targetCount; j++)
            //    {
               //         newStructSim.SetElement(targetCount * i + j, 0, structSimMatrix[i, j]);
            //    }

            //calculate R using power method (eigen vector)
            //==========================================

            int count = 0;
            while (count < 50)
            {
                //R = aAR + (1-2a)E1 + (1-2a)E2 where a = 0.333
                //newR = (((myA.Multiply(newR)).Multiply(0.333)).Add(newStructSim.Multiply(0.333))).Add(newSim.Multiply(0.333));//ommited to have name similarity only 17/4/2012
                newR = (((myA.Multiply(newR)).Multiply(0.5)).Add(newSim.Multiply(0.5)));

                double sum = 0;
                for (int i = 0; i < newR.RowDimension; i++)
                    for (int j = 0; j < newR.ColumnDimension; j++)
                        sum += newR.GetElement(i, j);

                newR = newR.Multiply(1.0 / sum);

                count++;
            }

            return newR.Array;
        }