예제 #1
0
        public static void cudaTranspose(ref MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm)
        {
            GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);

            GPGPUBLAS blas = GPGPUBLAS.Create(gpu);

            int cols = dm.ColumnCount, rows = dm.RowCount;
            int restRows = rows - cols;

            //double[] a = dm.Storage.ToColumnMajorArray();
            double[] a = dm.SubMatrix(0, cols, 0, cols).Storage.ToColumnMajorArray();
            double[] b = dm.SubMatrix(cols, restRows, 0, cols).Storage.ToColumnMajorArray();
            dm = null;

            double[] a_d = gpu.CopyToDevice <double>(a);
            a = null;
            double[] c_d = gpu.Allocate <double>(cols * cols);
            double[] x_d = gpu.CopyToDevice <double>(new double[] { 1 });
            blas.GEMV(cols, cols, 1, c_d, x_d, 0, x_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            a = new double[cols * rows];
            gpu.CopyFromDevice <double>(c_d, 0, a, 0, cols * cols);
            gpu.FreeAll();
            a_d = gpu.CopyToDevice <double>(b);
            b   = null;
            c_d = gpu.Allocate <double>(restRows * cols);
            x_d = gpu.CopyToDevice <double>(new double[] { 1 });
            blas.GEMV(restRows, cols, 1, c_d, x_d, 0, x_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            gpu.CopyFromDevice <double>(c_d, 0, a, cols * cols, restRows * cols);
            gpu.FreeAll();
            dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cols, rows, a);
        }
예제 #2
0
        public static void writeMatrixToFile(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix matrix, string file, System.Windows.Forms.RichTextBox tb1, MainForm frm)
        {
            System.IO.Stream       fileStream = new System.IO.FileStream(file, System.IO.FileMode.Create);
            System.IO.BinaryWriter bw         = new System.IO.BinaryWriter(fileStream, System.Text.Encoding.Default);
            double[]             arr          = matrix.ToColumnWiseArray();
            System.IO.TextWriter tr           = new System.IO.StreamWriter(file + ".metainfo");
            tr.WriteLine("Column count");
            tr.WriteLine(matrix.ColumnCount);
            tr.WriteLine("Row count");
            tr.WriteLine(matrix.RowCount);
            tr.Flush();
            tr.Close();
            int len = arr.Length;

            matrix = null;
            int index = 0;

            byte[] bytes = new byte[arr.Length * 8];
            foreach (double item in arr)
            {
                BitConverter.GetBytes(item).CopyTo(bytes, index);
                if (index / 8 / 500D == Math.Round(index / 8 / 500D))
                {
                    tb1.BeginInvoke(new MainForm.setProgressDel(frm.addVal), new object[] { (int)index / 8, len, "Записано" });
                }
                index += 8;
            }
            bw.Write(bytes);
            bw.Flush();
            tb1.BeginInvoke(new MainForm.setProgressDel(frm.addVal), new object[] { (int)0, len, "" });
            bw.Flush();
            bw.Close();
            fileStream.Close();
        }
예제 #3
0
        public static string matrixToString(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm, ReferenceSystem rs)
        {
            StringBuilder sb    = new StringBuilder();
            int           index = 0;

            for (int i = 0; i < 21; i++)
            {
                sb.AppendLine();
            }
            for (int i = 2; i <= rs.maxDegree; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    if (j != 0)
                    {
                        sb.AppendLine(string.Format("{0}\t{1}\t{2:0.000000000000e+00}\t{3:0.000000000000e+00}", i, j, dm.Values[index], dm.Values[index + 1]));
                        index += 2;
                    }
                    else
                    {
                        sb.AppendLine(string.Format("{0}\t{1}\t{2:0.000000000000e+00}\t{3:0.000000000000e+00}", i, j, dm.Values[index], 0));
                        index += 1;
                    }
                }
            }
            return(sb.ToString());
        }
예제 #4
0
        public static void cudaTranspose(ref MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm)
        {
            GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);

            GPGPUBLAS blas = GPGPUBLAS.Create(gpu);

            int cols = dm.ColumnCount, rows = dm.RowCount;
            int restRows = rows - cols;
            //double[] a = dm.Storage.ToColumnMajorArray();
            double[] a = dm.SubMatrix(0, cols, 0, cols).Storage.ToColumnMajorArray();
            double[] b = dm.SubMatrix(cols, restRows, 0, cols).Storage.ToColumnMajorArray();
            dm = null;

            double[] a_d = gpu.CopyToDevice<double>(a);
            a = null;
            double[] c_d = gpu.Allocate<double>(cols * cols);
            double[] x_d = gpu.CopyToDevice<double>(new double[] { 1 });
            blas.GEMV(cols, cols, 1, c_d, x_d, 0, x_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            a = new double[cols * rows];
            gpu.CopyFromDevice<double>(c_d, 0, a, 0, cols * cols);
            gpu.FreeAll();
            a_d = gpu.CopyToDevice<double>(b);
            b = null;
            c_d = gpu.Allocate<double>(restRows * cols);
            x_d = gpu.CopyToDevice<double>(new double[] { 1 });
            blas.GEMV(restRows, cols, 1, c_d, x_d, 0, x_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            gpu.CopyFromDevice<double>(c_d, 0, a, cols * cols, restRows * cols);
            gpu.FreeAll();
            dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cols, rows, a);
        }
예제 #5
0
        private Matrix <double> GetPointsMatrix()
        {
            Matrix <double> m = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, pointsList.Count);

            for (int i = 0; i < pointsList.Count; i++)
            {
                m[0, i] = pointsList[i].x;
                m[1, i] = pointsList[i].y;
                m[2, i] = pointsList[i].z;
            }
            return(m);
        }
예제 #6
0
        public BenchmarkMatrixMultiplication()
        {
            matrixA   = Matrix.CreateRandomMatrix(random, MATRIX_SIZE);
            matrixB   = Matrix.CreateRandomMatrix(random, MATRIX_SIZE);
            matrixRes = new Matrix(MATRIX_SIZE);

            mnMatrixA = (DenseMatrix)Matrix <double> .Build.Random(MATRIX_SIZE, MATRIX_SIZE);

            mnMatrixB = (DenseMatrix)Matrix <double> .Build.Random(MATRIX_SIZE, MATRIX_SIZE);

            mnMatrixRes = (DenseMatrix)Matrix <double> .Build.Dense(MATRIX_SIZE, MATRIX_SIZE);
        }
예제 #7
0
        public static void writeMatrixToTxtFile(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm, string file)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < dm.RowCount; i++)
            {
                foreach (var item in dm.SubMatrix(i, 1, 0, dm.ColumnCount).ToColumnWiseArray())
                {
                    sb.AppendFormat("{0,5:0.0000000000000e+00};", item);
                }
                sb.Append("\r\n");
            }
            System.IO.File.WriteAllText(file, sb.ToString());
        }
예제 #8
0
 public static void cudaTransposeAndMultiply(ref MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm)
 {
     Cudafy.CudafyModule km = Cudafy.Translator.CudafyTranslator.Cudafy();
     km.Serialize();
     GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);
     int cols = dm.ColumnCount, rows = dm.RowCount;
     dm.Storage.ToColumnMajorArray();
     double[] a = dm.ToColumnWiseArray();
     dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(1, 1);
     double[] dev_a = gpu.Allocate<double>(a.Length);
     GPGPUBLAS blas = GPGPUBLAS.Create(gpu);
     double[] a_d = gpu.CopyToDevice<double>(a);
     double[] c_d = gpu.Allocate<double>(cols * cols);
     gpu.StartTimer();
     blas.GEMM(cols, rows, cols, 1, a_d, a_d, 0, c_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
     a = new double[cols * cols];
     gpu.CopyFromDevice<double>(c_d, a);
     gpu.FreeAll();
     dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cols, cols, a);
 }
예제 #9
0
        public static MathNet.Numerics.LinearAlgebra.Double.DenseMatrix readDenceMatrixFromBinFile(string file, MainForm.setProgressDel d)
        {
            string[]               meta = System.IO.File.ReadAllLines(file + ".metainfo");
            System.IO.FileStream   fs   = new System.IO.FileStream(file, System.IO.FileMode.Open);
            System.IO.BinaryReader br   = new System.IO.BinaryReader(fs, System.Text.Encoding.Default);
            int cols = int.Parse(meta[1]);
            int rows = int.Parse(meta[3]);

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(rows, cols);
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    dm[i, j] = br.ReadDouble();
                }
                d.Invoke(br.BaseStream.Position / br.BaseStream.Length, 1, "Завантаження");
            }
            br.Close();
            fs.Close();
            return(dm);
        }
예제 #10
0
        public RegisteredCamera(float FocalLength, float k1, float k2, Matrix RotationMatrix, Vector3 TranslationVector, int ImageHeight, int ImageWidth)
        {
            this.FocalLength       = FocalLength;
            this.k1                = k1;
            this.k2                = k2;
            this.RotationMatrix    = RotationMatrix;
            this.TranslationVector = TranslationVector;
            this.ImageHeight       = ImageHeight;
            this.ImageWidth        = ImageWidth;

            Double[,] aTranslationMatrix = new Double[3, 1];
            aTranslationMatrix[0, 0]     = TranslationVector.X;
            aTranslationMatrix[1, 0]     = TranslationVector.Y;
            aTranslationMatrix[2, 0]     = TranslationVector.Z;


            Double[,] aRotationMatrix = new Double[3, 3];
            aRotationMatrix[0, 0]     = RotationMatrix.M11;
            aRotationMatrix[0, 1]     = RotationMatrix.M12;
            aRotationMatrix[0, 2]     = RotationMatrix.M13;
            aRotationMatrix[1, 0]     = RotationMatrix.M21;
            aRotationMatrix[1, 1]     = RotationMatrix.M22;
            aRotationMatrix[1, 2]     = RotationMatrix.M23;
            aRotationMatrix[2, 0]     = RotationMatrix.M31;
            aRotationMatrix[2, 1]     = RotationMatrix.M32;
            aRotationMatrix[2, 2]     = RotationMatrix.M33;

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseRotationMatrix    = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(aRotationMatrix);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseTranslationMatrix = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(aTranslationMatrix);

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix densePositionVector = (-(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Transpose()) * denseTranslationMatrix;

            PositionVector = new Vector3((float)densePositionVector[0, 0], (float)densePositionVector[1, 0], (float)densePositionVector[2, 0]);

            //denseTranslationMatrix = -(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Transpose() * denseTranslationMatrix;

            //TranslationVector.X = (float)denseTranslationMatrix[0, 0];
            //TranslationVector.Y = (float)denseTranslationMatrix[1, 0];
            //TranslationVector.Z = (float)denseTranslationMatrix[2, 0];
        }
예제 #11
0
        private double[] Polyfit(double[] x, double[] y, int degree)
        {
            // Vandermonde matrix
            var v = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(x.Length, degree + 1);

            for (int i = 0; i < v.RowCount; i++)
            {
                for (int j = 0; j <= degree; j++)
                {
                    v[i, j] = Math.Pow(x[i], j);
                }
            }
            var         yv = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(y).ToColumnMatrix();
            QR <double> qr = v.QR(QRMethod.Full);
            // Math.Net doesn't have an "economy" QR, so:
            // cut R short to square upper triangle, then recompute Q
            var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
            var q = v.Multiply(r.Inverse());
            var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));

            return(p.Column(0).ToArray());
        }
예제 #12
0
        public static void cudaTransposeAndMultiply(ref MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm)
        {
            Cudafy.CudafyModule km = Cudafy.Translator.CudafyTranslator.Cudafy();
            km.Serialize();
            GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);
            int   cols = dm.ColumnCount, rows = dm.RowCount;

            dm.Storage.ToColumnMajorArray();
            double[] a = dm.ToColumnWiseArray();
            dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(1, 1);
            double[]  dev_a = gpu.Allocate <double>(a.Length);
            GPGPUBLAS blas  = GPGPUBLAS.Create(gpu);

            double[] a_d = gpu.CopyToDevice <double>(a);
            double[] c_d = gpu.Allocate <double>(cols * cols);
            gpu.StartTimer();
            blas.GEMM(cols, rows, cols, 1, a_d, a_d, 0, c_d, Cudafy.Maths.BLAS.Types.cublasOperation.T);
            a = new double[cols * cols];
            gpu.CopyFromDevice <double>(c_d, a);
            gpu.FreeAll();
            dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cols, cols, a);
        }
예제 #13
0
        public RegisteredCamera(float FocalLength, float k1, float k2, Matrix RotationMatrix, Vector3 TranslationVector, int ImageHeight, int ImageWidth)
        {
            this.FocalLength = FocalLength;
            this.k1 = k1;
            this.k2 = k2;
            this.RotationMatrix = RotationMatrix;
            this.TranslationVector = TranslationVector;
            this.ImageHeight = ImageHeight;
            this.ImageWidth = ImageWidth;

            Double[,] aTranslationMatrix = new Double[3, 1];
            aTranslationMatrix[0, 0] = TranslationVector.X;
            aTranslationMatrix[1, 0] = TranslationVector.Y;
            aTranslationMatrix[2, 0] = TranslationVector.Z;

            Double[,] aRotationMatrix = new Double[3, 3];
            aRotationMatrix[0, 0] = RotationMatrix.M11;
            aRotationMatrix[0, 1] = RotationMatrix.M12;
            aRotationMatrix[0, 2] = RotationMatrix.M13;
            aRotationMatrix[1, 0] = RotationMatrix.M21;
            aRotationMatrix[1, 1] = RotationMatrix.M22;
            aRotationMatrix[1, 2] = RotationMatrix.M23;
            aRotationMatrix[2, 0] = RotationMatrix.M31;
            aRotationMatrix[2, 1] = RotationMatrix.M32;
            aRotationMatrix[2, 2] = RotationMatrix.M33;

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseRotationMatrix = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(aRotationMatrix);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseTranslationMatrix = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(aTranslationMatrix);

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix densePositionVector = (-(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Transpose()) * denseTranslationMatrix;

            PositionVector = new Vector3((float)densePositionVector[0, 0], (float)densePositionVector[1, 0], (float)densePositionVector[2, 0]);

            //denseTranslationMatrix = -(MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Transpose() * denseTranslationMatrix;

            //TranslationVector.X = (float)denseTranslationMatrix[0, 0];
            //TranslationVector.Y = (float)denseTranslationMatrix[1, 0];
            //TranslationVector.Z = (float)denseTranslationMatrix[2, 0];
        }
예제 #14
0
파일: Program.cs 프로젝트: holymosh/labs
 public void Task8()
 {
     using (var reader = new StreamReader(@"C:\Users\MI\Documents\labs\Numerical Methods\Numerical Methods\Extension\LU.txt"))
     {
         var size     = Int32.Parse(reader.ReadLine());
         var matrix   = new double[size, size];
         var vertical = new double[size];
         for (int i = 0; i < size; i++)
         {
             var values = reader.ReadLine().Split(' ');
             for (int j = 0; j < size; j++)
             {
                 matrix[i, j] = double.Parse(values[j]);
             }
         }
         var A       = Matrix.OfArray(matrix);
         var splited = reader.ReadLine().Split(' ');
         for (int i = 0; i < size; i++)
         {
             vertical[i] = double.Parse(splited[i]);
         }
         var lu = A.LU();
         lu.Inverse().Print("inversed");
         var l = lu.L;
         var u = lu.U;
         var B = new Matrix(size, 1);
         for (int i = 0; i < size; i++)
         {
             B[i, 0] = vertical[i];
         }
         var solved = lu.Solve(B);
         l.Print("L");
         u.Print("U");
         solved.Print("solved");
     }
 }
예제 #15
0
        /// <summary>
        /// Find Homography.
        /// </summary>
        /// <param name="source"> The source Transformer. </param>
        /// <param name="destination"> The destination Transformer. </param>
        /// <returns> The homologous matrix. </returns>
        public static Matrix3x2 FindHomography(ITransformerLTRB source, ITransformerLTRB destination)
        {
            float x0 = source.LeftTop.X, x1 = source.RightTop.X, x2 = source.LeftBottom.X, x3 = source.RightBottom.X;
            float y0 = source.LeftTop.Y, y1 = source.RightTop.Y, y2 = source.LeftBottom.Y, y3 = source.RightBottom.Y;
            float u0 = destination.LeftTop.X, u1 = destination.RightTop.X, u2 = destination.LeftBottom.X, u3 = destination.RightBottom.X;
            float v0 = destination.LeftTop.Y, v1 = destination.RightTop.Y, v2 = destination.LeftBottom.Y, v3 = destination.RightBottom.Y;

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix matrix = MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.OfArray(new double[008, 008]
            {
                { x0, y0, 1, 0, 0, 0, -u0 * x0, -u0 * y0 },
                { 0, 0, 0, x0, y0, 1, -v0 * x0, -v0 * y0 },
                { x1, y1, 1, 0, 0, 0, -u1 * x1, -u1 * y1 },
                { 0, 0, 0, x1, y1, 1, -v1 * x1, -v1 * y1 },
                { x3, y3, 1, 0, 0, 0, -u3 * x3, -u3 * y3 },
                { 0, 0, 0, x3, y3, 1, -v3 * x3, -v3 * y3 },
                { x2, y2, 1, 0, 0, 0, -u2 * x2, -u2 * y2 },
                { 0, 0, 0, x2, y2, 1, -v2 * x2, -v2 * y2 },
            });

            MathNet.Numerics.LinearAlgebra.Double.DenseVector vector = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(new double[008]
            {
                u0, v0, u1, v1,
                u3, v3, u2, v2
            });

            MathNet.Numerics.LinearAlgebra.Matrix <double> PseudoInverse = Transformer.PseudoInverse2(matrix);

            MathNet.Numerics.LinearAlgebra.Vector <double> ret = Transformer.Multiply2(PseudoInverse, vector);

            return(new Matrix3x2
                   (
                       m11: (float)ret[0], m12: (float)ret[3],
                       m21: (float)ret[1], m22: (float)ret[4],
                       m31: (float)ret[2], m32: (float)ret[5]
                   ));
        }
예제 #16
0
 private double[] single_correction(double[] coefs, double xdata, double ydata, double zdata)
 {
     double[] result = new double[3];
     MathNet.Numerics.LinearAlgebra.Double.Matrix B = new MathNet.Numerics.LinearAlgebra.Double.DiagonalMatrix(3, 3, 1);
     MathNet.Numerics.LinearAlgebra.Double.Matrix A = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, 3);
     A.At(0, 0, coefs[0]);
     A.At(0, 1, coefs[3]);
     A.At(0, 2, coefs[4]);
     A.At(1, 0, coefs[5]);
     A.At(1, 1, coefs[1]);
     A.At(1, 2, coefs[6]);
     A.At(2, 0, coefs[7]);
     A.At(2, 1, coefs[8]);
     A.At(2, 2, coefs[2]);
     MathNet.Numerics.LinearAlgebra.Double.Matrix B1 = Kalman_class.Matrix_Minus(B, A);
     MathNet.Numerics.LinearAlgebra.Double.Matrix C = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, 1);
     C.At(0, 0, xdata);
     C.At(1, 0, ydata);
     C.At(2, 0, zdata);
     MathNet.Numerics.LinearAlgebra.Double.Matrix D = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, 1);
     D.At(0, 0, coefs[9]);
     D.At(1, 0, coefs[10]);
     D.At(2, 0, coefs[11]);
     MathNet.Numerics.LinearAlgebra.Double.Matrix res = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, 1);
     res = Kalman_class.Matrix_Mult(B1, Kalman_class.Matrix_Minus(C, D));
     result[0] = res.At(0, 0);
     result[1] = res.At(1, 0);
     result[2] = res.At(2, 0);
     return result;
 }
예제 #17
0
파일: Program.cs 프로젝트: holymosh/labs
        public void Task5()
        {
            // qr
            Console.WriteLine("qr");
            var A = Matrix.OfArray(new double[4, 4]
            {
                { 8, 2, 3, 1 },
                { 2, 8, 1, 2 },
                { 1, 2, 8, 4 },
                { 1, 1, 1, 7 }
            });
            var B = Matrix.OfArray(new double[4, 1]
            {
                { 1 },
                { 2 },
                { 2 },
                { 3 }
            });
            var qr = A.QR();
            var q  = qr.Q;
            var r  = qr.R;

            Console.WriteLine("Q");
            Console.WriteLine();
            for (int i = 0; i < q.RowCount; i++)
            {
                for (int j = 0; j < q.ColumnCount; j++)
                {
                    Console.Write(q[i, j] + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine("R");
            Console.WriteLine();
            for (int i = 0; i < r.RowCount; i++)
            {
                for (int j = 0; j < r.ColumnCount; j++)
                {
                    Console.Write(r[i, j] + " ");
                }
                Console.WriteLine();
            }
            var solvedViaQr = qr.Solve(B);

            Console.WriteLine("result");
            for (int i = 0; i < solvedViaQr.RowCount; i++)
            {
                for (int j = 0; j < solvedViaQr.ColumnCount; j++)
                {
                    Console.Write(solvedViaQr[i, j] + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine("solved via Iteration");
            Console.WriteLine();
            var solvedViaIteration = A.SolveViaIterationMethod(B);

            for (int i = 0; i < solvedViaIteration.RowCount; i++)
            {
                for (int j = 0; j < solvedViaIteration.ColumnCount; j++)
                {
                    Console.Write(solvedViaIteration[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
예제 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="p"></param>
        /// <param name="q"></param>
        /// <returns></returns>
        public static Matrix3D Rigid3D(IList <Vector3D> p, IList <Vector3D> q)
        {
            int n = p.Count;

            double[] m = new double[9];
            for (int i = 0; i < n; i++)
            {
                m[0] += p[i].X * q[i].X;
                m[1] += p[i].X * q[i].Y;
                m[2] += p[i].X * q[i].Z;
                m[3] += p[i].Y * q[i].X;
                m[4] += p[i].Y * q[i].Y;
                m[5] += p[i].Y * q[i].Z;
                m[6] += p[i].Z * q[i].X;
                m[7] += p[i].Z * q[i].Y;
                m[8] += p[i].Z * q[i].Z;
            }

            var M = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, 3, m);
            //double[] S = new double[3];
            //double[] U = new double[9];
            //double[] VT = new double[9];
            //mklSolver.SingularValueDecomposition(true, M.Data, 3, 3, S, U, VT);
            //var RR = new Matrix3D()
            //{
            //    M11 = U[0] * VT[0] + U[1] * VT[3] * U[2] * VT[6],
            //    M12 = U[0] * VT[1] + U[1] * VT[4] * U[2] * VT[7],
            //    M13 = U[0] * VT[2] + U[1] * VT[5] * U[2] * VT[8],

            //    M21 = U[3] * VT[0] + U[4] * VT[3] * U[5] * VT[6],
            //    M22 = U[3] * VT[1] + U[4] * VT[4] * U[5] * VT[7],
            //    M23 = U[3] * VT[2] + U[4] * VT[5] * U[5] * VT[8],

            //    M31 = U[6] * VT[0] + U[7] * VT[3] * U[8] * VT[6],
            //    M32 = U[6] * VT[1] + U[7] * VT[4] * U[8] * VT[7],
            //    M33 = U[6] * VT[2] + U[7] * VT[5] * U[8] * VT[8],
            //};
            //return RR;

            // R = V*UT <==> RT = VT*U
            var svd = M.Svd(true);
            var RT  = svd.U().Multiply(svd.VT());
            var R   = new Matrix3D()
            {
                M11 = RT[0, 0],
                M12 = RT[1, 0],
                M13 = RT[2, 0],
                M21 = RT[0, 1],
                M22 = RT[1, 1],
                M23 = RT[2, 1],
                M31 = RT[0, 2],
                M32 = RT[1, 2],
                M33 = RT[2, 2],
                //M11 = RT[0, 0],
                //M12 = RT[0, 1],
                //M13 = RT[0, 2],
                //M21 = RT[1, 0],
                //M22 = RT[1, 1],
                //M23 = RT[1, 2],
                //M31 = RT[2, 0],
                //M32 = RT[2, 1],
                //M33 = RT[2, 2],
                M44 = 1.0,
            };

            return(R);
        }
예제 #19
0
        public Vector3 ImageToWorld(double u, double v, double w, bool transposeRot, bool negateRot, bool invertRot, bool invertZ, float rotAngleX, float rotAngleY, float rotAngleZ)
        {
            double xprime = (u - ((float)(ImageWidth / 2))) / FocalLength;
            double yprime = (v - ((float)(ImageHeight / 2))) / FocalLength;

            //double xprime = (u) / FocalLength;
            //double yprime = (v) / FocalLength;

            if (invertZ)
            {
                w = -w;
            }

            double x = xprime * w;
            double y = yprime * w;
            double z = w;

            Double[,] homoXYZ = new Double[3, 1];
            homoXYZ[0, 0] = x;
            homoXYZ[1, 0] = y;
            homoXYZ[2, 0] = z;

            Double[,] TranslationMatrix = new Double[3, 1];
            TranslationMatrix[0, 0] = PositionVector.X;
            TranslationMatrix[1, 0] = PositionVector.Y;
            TranslationMatrix[2, 0] = PositionVector.Z;

            Double[,] aRotationMatrix = new Double[3, 3];
            aRotationMatrix[0, 0] = RotationMatrix.M11;
            aRotationMatrix[0, 1] = RotationMatrix.M12;
            aRotationMatrix[0, 2] = RotationMatrix.M13;
            aRotationMatrix[1, 0] = RotationMatrix.M21;
            aRotationMatrix[1, 1] = RotationMatrix.M22;
            aRotationMatrix[1, 2] = RotationMatrix.M23;
            aRotationMatrix[2, 0] = RotationMatrix.M31;
            aRotationMatrix[2, 1] = RotationMatrix.M32;
            aRotationMatrix[2, 2] = RotationMatrix.M33;

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseHomoXYZ = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(homoXYZ);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseTranslationMatrix = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(TranslationMatrix);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseRotationMatrix = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(aRotationMatrix);

            if (transposeRot)
            {
                denseRotationMatrix = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Transpose();
            }

            if (invertRot)
            {
                denseRotationMatrix = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Inverse();
            }
            denseRotationMatrix = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Inverse();

            if (negateRot)
            {
                denseRotationMatrix = -denseRotationMatrix;
            }

            //Double[,] TranslationMatrix = new Double[3, 1];
            //TranslationMatrix[0, 0] = TranslationVector.X;
            //TranslationMatrix[1, 0] = TranslationVector.Y;
            //TranslationMatrix[2, 0] = TranslationVector.Z;

            //denseRotationMatrix = denseRotationMatrix.Transpose() *

            //MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseWorldCoordinates = InverseRotationMatrix * (denseHomoXYZ - TranslationMatrix);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseWorldCoordinates = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)(denseRotationMatrix) * (denseHomoXYZ - denseTranslationMatrix);

            float worldX = (float)denseWorldCoordinates[0, 0];
            float worldY = (float)denseWorldCoordinates[1, 0];
            float worldZ = (float)denseWorldCoordinates[2, 0];

            //Microsoft.Xna.Framework.Matrix rotX;
            //Microsoft.Xna.Framework.Matrix rotY;
            //Microsoft.Xna.Framework.Matrix rotZ;
            //Vector3 origin = new Vector3(0, 0, 0);
            //Microsoft.Xna.Framework.Matrix.CreateRotationX((float)rotAngleX, out rotX);
            //Microsoft.Xna.Framework.Matrix.CreateRotationY((float)rotAngleY, out rotY);
            //Microsoft.Xna.Framework.Matrix.CreateRotationZ((float)rotAngleZ, out rotZ);
            //Vector3 tempV = new Vector3((float)worldX, (float)worldY, (float)worldZ);
            //tempV = Vector3.Transform(tempV, rotX);
            //tempV = Vector3.Transform(tempV, rotY);
            //tempV = Vector3.Transform(tempV, rotZ);

            //worldX = tempV.X;
            //worldY = tempV.Y;
            //worldZ = tempV.Z;

            Vector3 WorldCoodrinates = new Vector3(worldX, worldY, worldZ);

            return WorldCoodrinates;
        }
예제 #20
0
        private void button4_Click(object sender, EventArgs e)
        {
            Action fileProc = () =>
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                MathNet.Numerics.Control.LinearAlgebraProvider         = new MathNet.Numerics.Algorithms.LinearAlgebra.Mkl.MklLinearAlgebraProvider();
                MathNet.Numerics.Control.NumberOfParallelWorkerThreads = Environment.ProcessorCount;
                addText("Обробка файлу вимірювань...\r\n");
                double[][] SGG_data = null;
                if (System.IO.File.Exists("sgg_data.bin"))
                {
                    SGG_data = IOFunc.binLoad_SGG_data("sgg_data.bin");
                }
                else
                {
                    SGG_data = Data.IOFunc.read_SGG_data(SphericalHarmonicAnalyze.Properties.Settings.Default.SGG_measures, new setProgressDel(addVal));
                    IOFunc.binwrite_SGG_data("sgg_data.bin", SGG_data);
                }
                addText("Дані вимірювань оброблено: {0} шт.\r\n", SGG_data.Length); Thread.Sleep(500);
                ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.TideFree);
                elipsoid.gridParameters.cellSize         = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize;
                elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude;
                elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder;
                int             greedColumnsCount, greedRowsCount;
                List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds, 180 - elipsoid.gridParameters.coLatitudeBounds);
                addText("Сітку згенеровано: {0} комірок \r\n", greed.Count);
                double       avgR = MathFunc.getAvgRadius(SGG_data);
                List <int>[] map  = MathFunc.getMappingOfPoints(elipsoid, SGG_data, greed.ToArray(), greedRowsCount, greedColumnsCount, avgR); sw.Stop(); addText("Точки віднесено до комірок сітки за: {0}.\r\n", sw.Elapsed.ToString());
                addText("Кількість клітинок сітки всього: {0}\r\n", greed.Count);
                int res1 = 0; foreach (var item in map)
                {
                    res1 += item.Count;
                }
                addText("Використано вимірів: {0}\r\nСер радіус: {1}\r\n", res1, avgR);
                test.checkMap(SGG_data, map, greed, elipsoid);
                List <int>[] newMap = null;
                MathFunc.checkGreed(ref greed, map, out newMap);
                addText("Кількість клітинок сітки, в яких присутні дані вимірювань: {0}\r\n", greed.Count);
                map = newMap; newMap = null;
                IOFunc.writeGreedToCsvFileWithMeasureCount(greed, map, "greed_new_map.txt");
                double[] avgRadius; sw.Restart();
                double[] regularisedValues = MathFunc.regularization(SGG_data, greed.ToArray(), map, out avgRadius); sw.Stop(); addText("Регуляризація (на основі сферичної відстані) виконана за: {0}.\r\n", sw.Elapsed.ToString());
                IOFunc.writeGreedToCsvFileWithMeasureS(greed, regularisedValues, "greed_regular_grad.txt");
                avgRadius[0]             = Math.Round(avgRadius[0]);
                elipsoid.satelliteSphere = avgRadius[0];
                addText("Середній радіус: {0,10:0.000}.\r\nМінімальний радіус: {1,10:0.0000}\r\nМаксимальний радіус:{2,10:0.0000}\r\n", avgRadius[0], avgRadius[1], avgRadius[2]);
                SGG_data = null; map = null;
                int[][] t_nm = MathFunc.get_nm(elipsoid.maxDegree);
                sw.Restart();
                MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(greed.Count, (MathFunc.getArraySize(elipsoid.maxDegree) - 3) * 2 - (elipsoid.maxDegree - 1));
                sw.Stop(); addText("Пам'ять для матриці коефіцієнтів виділено за: {0}.\r\n", sw.Elapsed.ToString());
                sw.Restart();
                int progress = 0;
                //Обчислення елементів матриці
                var p = Parallel.For(0, dm.RowCount, (i) =>
                {
                    double[] line = MathFunc.getCoefMatrixLineKoop(elipsoid, elipsoid.maxDegree, t_nm, elipsoid.satelliteSphere, greed[i][0], greed[i][1]);
                    lock (dm)
                    {
                        dm.SetRow(i, line);
                    }
                    progress++;
                    if (progress / 100D == Math.Round(progress / 100D))
                    {
                        addVal(progress, dm.RowCount, "Визначено");
                    }
                });

                if (!p.IsCompleted)
                {
                    throw new Exception("Parallel.For");
                }
                ;
                IOFunc.writeMatrixToMatLabFile(dm, @"matlab\A.mat", "A");
                sw.Stop();
                richTextBox1.Invoke(new setProgressDel(addVal), new object[] { 0, dm.RowCount, "" });
                addText("Матриця {0} на {1} ({2}MB) згенерована за: {3,10}\r\n", dm.RowCount, dm.ColumnCount, dm.ColumnCount * dm.RowCount * 8 / 1000000, sw.Elapsed.ToString() /* + "\r\nЗапис у файл...\r\n"*/);
                if (true)
                {
                    GravityModel gm08 = new GravityModel(elipsoid.maxDegree);
                    gm08.loadFromFile("GO_CONS_EGM_GCF_2.gfc", new setProgressDel(addVal));
                    MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm08.getGradientForGrid(elipsoid, greed));//regularisedValues);
                    MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL2;
                    GravityModel gm = new GravityModel(elipsoid.maxDegree);
                    if (radioButton1.Checked)
                    {
                        sw.Restart();
                        gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
                        sw.Stop(); addText("Вихідна модель завантажена за: {0}.\r\n", sw.Elapsed.ToString());
                        sw.Restart();
                        dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed));
                        sw.Stop(); addText("Градієнти за вихідною моделлю обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                    }
                    else
                    {
                        sw.Restart();
                        gm   = GravityModel.getNormalModel(elipsoid, elipsoid.maxDegree);
                        dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed));
                        sw.Stop(); addText("Нормальні градієнти обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                    }
                    dmL  = dmL - dmL2;
                    dmL2 = null;
                    IOFunc.writeMatrixToMatLabFile(dmL.ToColumnMatrix(), @"matlab\L.mat", "L");
                    sw.Restart();
                    MathNet.Numerics.LinearAlgebra.Double.DenseVector dmLNormal = null;
                    dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dm.TransposeThisAndMultiply(dmL);
                    dmL       = null;
                    IOFunc.writeMatrixToMatLabFile(dmLNormal.ToColumnMatrix(), @"matlab\LNorm.mat", "LNorm");
                    sw.Stop(); addText("Стовпчик вільних членів обчислений за: {0}.\r\n", sw.Elapsed.ToString());
                    MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dmANorm = null;
                    sw.Restart();
                    dmANorm = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)dm.TransposeThisAndMultiply(dm); dm = null;
                    sw.Stop(); addText("Нормальна матриця коефіціэнтів обчислена за: {0}.\r\n", sw.Elapsed.ToString());
                    IOFunc.writeMatrixToMatLabFile(dmANorm, @"matlab\ANorm.mat", "ANorm");
                    //dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dmLNormal.Multiply(5e-8);
                    var x   = dmANorm.Inverse();
                    var res = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)x.Multiply(dmLNormal);
                    IOFunc.writeModeVectorlToTxtFile(res, elipsoid, @"matlab\_out.AL");
                    addText(@"Результат за методом A\L знайдено...");
                    x = null;
                    GravityModel gm_R = new GravityModel(gm);
                    gm_R.addDeltaCoef(res.ToArray()); res = null;
                    double[] h  = GravityModel.getGeoidHeight(elipsoid, gm_R, greed);
                    double[] dg = GravityModel.getAnomaly(elipsoid, gm_R, greed);
                    IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, @"output\result_AL.txt");
                    IOFunc.writeGravityModelToTxtFile(gm_R, @"output\model_AL.gcf");
                    sw.Restart();
                    addText(dmANorm.Rank().ToString() + "\r\n");
                    dmANorm   = null;
                    dmLNormal = null;
                    sw.Stop(); addText("Невідомі знайдено за: {0}.\r\n", sw.Elapsed.ToString());
                }
            };

            if (System.IO.File.Exists(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel))
            {
                tabControl1.SelectedTab = tabControl1.TabPages[1];
                this.UseWaitCursor      = true;
                ts  = new CancellationTokenSource();
                ct  = ts.Token;
                tsk = Task.Factory.StartNew(fileProc, ct);
                var setCur = Task.Factory.StartNew(() => { tsk.Wait(); this.UseWaitCursor = false; addText("Обчислення завершені!"); });
                richTextBox1.SaveFile(@"output\zvit.rtf");
            }
        }
예제 #21
0
        public double Determinant()
        {
            if (!IsMatrixQuadratic())
            {
                throw new Exception("Für die Berechnung der Determinante muss die Matrix quadratisch sein!");
            }

            //Math.net Library
            MathNetLAGen.Matrix<double> netMatrix = new MathNetLA.Double.DenseMatrix(ToArray());
            return netMatrix.Determinant();
        }
예제 #22
0
        public Vector3 ImageToWorld(double u, double v, double w, bool transposeRot, bool negateRot, bool invertRot, bool invertZ, float rotAngleX, float rotAngleY, float rotAngleZ)
        {
            double xprime = (u - ((float)(ImageWidth / 2))) / FocalLength;
            double yprime = (v - ((float)(ImageHeight / 2))) / FocalLength;

            //double xprime = (u) / FocalLength;
            //double yprime = (v) / FocalLength;

            if (invertZ)
            {
                w = -w;
            }

            double x = xprime * w;
            double y = yprime * w;
            double z = w;

            Double[,] homoXYZ = new Double[3, 1];
            homoXYZ[0, 0]     = x;
            homoXYZ[1, 0]     = y;
            homoXYZ[2, 0]     = z;

            Double[,] TranslationMatrix = new Double[3, 1];
            TranslationMatrix[0, 0]     = PositionVector.X;
            TranslationMatrix[1, 0]     = PositionVector.Y;
            TranslationMatrix[2, 0]     = PositionVector.Z;


            Double[,] aRotationMatrix = new Double[3, 3];
            aRotationMatrix[0, 0]     = RotationMatrix.M11;
            aRotationMatrix[0, 1]     = RotationMatrix.M12;
            aRotationMatrix[0, 2]     = RotationMatrix.M13;
            aRotationMatrix[1, 0]     = RotationMatrix.M21;
            aRotationMatrix[1, 1]     = RotationMatrix.M22;
            aRotationMatrix[1, 2]     = RotationMatrix.M23;
            aRotationMatrix[2, 0]     = RotationMatrix.M31;
            aRotationMatrix[2, 1]     = RotationMatrix.M32;
            aRotationMatrix[2, 2]     = RotationMatrix.M33;

            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseHomoXYZ           = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(homoXYZ);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseTranslationMatrix = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(TranslationMatrix);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseRotationMatrix    = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(aRotationMatrix);

            if (transposeRot)
            {
                denseRotationMatrix = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Transpose();
            }

            if (invertRot)
            {
                denseRotationMatrix = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Inverse();
            }
            denseRotationMatrix = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)denseRotationMatrix.Inverse();

            if (negateRot)
            {
                denseRotationMatrix = -denseRotationMatrix;
            }

            //Double[,] TranslationMatrix = new Double[3, 1];
            //TranslationMatrix[0, 0] = TranslationVector.X;
            //TranslationMatrix[1, 0] = TranslationVector.Y;
            //TranslationMatrix[2, 0] = TranslationVector.Z;

            //denseRotationMatrix = denseRotationMatrix.Transpose() *

            //MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseWorldCoordinates = InverseRotationMatrix * (denseHomoXYZ - TranslationMatrix);
            MathNet.Numerics.LinearAlgebra.Double.DenseMatrix denseWorldCoordinates = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)(denseRotationMatrix) * (denseHomoXYZ - denseTranslationMatrix);

            float worldX = (float)denseWorldCoordinates[0, 0];
            float worldY = (float)denseWorldCoordinates[1, 0];
            float worldZ = (float)denseWorldCoordinates[2, 0];



            //Microsoft.Xna.Framework.Matrix rotX;
            //Microsoft.Xna.Framework.Matrix rotY;
            //Microsoft.Xna.Framework.Matrix rotZ;
            //Vector3 origin = new Vector3(0, 0, 0);
            //Microsoft.Xna.Framework.Matrix.CreateRotationX((float)rotAngleX, out rotX);
            //Microsoft.Xna.Framework.Matrix.CreateRotationY((float)rotAngleY, out rotY);
            //Microsoft.Xna.Framework.Matrix.CreateRotationZ((float)rotAngleZ, out rotZ);
            //Vector3 tempV = new Vector3((float)worldX, (float)worldY, (float)worldZ);
            //tempV = Vector3.Transform(tempV, rotX);
            //tempV = Vector3.Transform(tempV, rotY);
            //tempV = Vector3.Transform(tempV, rotZ);



            //worldX = tempV.X;
            //worldY = tempV.Y;
            //worldZ = tempV.Z;


            Vector3 WorldCoodrinates = new Vector3(worldX, worldY, worldZ);

            return(WorldCoodrinates);
        }
예제 #23
0
파일: Program.cs 프로젝트: sinilya/client
        public static void ReceiveMessage()
        {
            while (true)
            {
                try
                {
                    byte[]        data    = new byte[64];
                    StringBuilder builder = new StringBuilder();
                    int           bytes   = 0;
                    do
                    {
                        bytes = stream.Read(data, 0, data.Length);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }while (stream.DataAvailable);

                    string        message = builder.ToString();
                    serverMessage sm      = JsonConvert.DeserializeObject <serverMessage>(message);
                    switch (sm.type)
                    {
                    case "messageerror":
                        Console.WriteLine("Ошибка, сообщение невозможно отправить: " + sm.data);
                        break;

                    case "usersonline":
                        string[] usersList = sm.data.Split('|');
                        Console.WriteLine("Список пользователей онлайн:");
                        for (int i = 1; i <= usersList.Length; i++)
                        {
                            Console.WriteLine(i.ToString() + ". " + usersList[i - 1]);
                        }
                        break;

                    case "rejectconnection":
                        Console.WriteLine("Невозможно установить соединение: " + sm.data);
                        break;

                    case "connections":
                        string[] onlineConnections = sm.data.Split('|');
                        if (onlineConnections[0] == "")
                        {
                            Console.WriteLine("Подключения отсутствуют");
                            break;
                        }
                        Console.WriteLine("Текущие подключения:");
                        for (int i = 0; i < onlineConnections.Length; i++)
                        {
                            Console.WriteLine(i + ". " + onlineConnections[i]);
                        }
                        break;

                    case "alreadydisconnected":
                        Console.WriteLine("Пользователь " + sm.data + " не подключен");
                        break;

                    case "removeconnection":
                        Console.WriteLine("Пользователь " + sm.data + " отключен");
                        break;

                    case "connectionremoved":
                        Console.WriteLine("Пользователь " + sm.data + " отключился");
                        break;

                    case "acceptconnection":
                        Console.WriteLine("Пользователь " + sm.data + " устанавливает соединение...");
                        clientMessage cm = new clientMessage()
                        {
                            type = "accept", data = sm.data
                        };
                        string json = JsonConvert.SerializeObject(cm);
                        Console.WriteLine("JSON :  " + json);
                        sendMessage(json);
                        break;

                    case "accept":
                        string[] keys               = sm.data.Split('|');
                        string   mySecretKey        = keys[1];
                        string   companionPublicKey = keys[2];
                        string[] mscdataString      = mySecretKey.Split(' ');
                        string[] cpkdataString      = companionPublicKey.Split(' ');
                        double[] mscdata            = new double[mscdataString.Length];
                        double[] cpkdata            = new double[cpkdataString.Length];
                        for (int i = 0; i < mscdataString.Length; i++)
                        {
                            mscdata[i] = Int32.Parse(mscdataString[i]);
                            cpkdata[i] = Int32.Parse(cpkdataString[i]);
                        }
                        Matrix <double> msc = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(mscdata.Length, 1, mscdata);
                        Matrix <double> cpk = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(cpkdata.Length, 1, cpkdata);
                        //Console.WriteLine("MY SEC: " + msc.ToString());
                        //Console.WriteLine("IT PUB: " + cpk.ToString());

                        msc = msc.Transpose();
                        Matrix <double> sKey = msc.Multiply(cpk);
                        sKey = sKey.Modulus(50);

                        commonSecretKey = (int)sKey[0, 0];
                        //Console.WriteLine("RES: " + Convert.ToString(commonSecretKey));


                        string     Digits  = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
                        byte[]     data123 = BitConverter.GetBytes(commonSecretKey);
                        BigInteger intData = 0;
                        for (int i = 0; i < data123.Length; i++)
                        {
                            intData = intData * 256 + data123[i];
                        }
                        string result = "";
                        while (intData > 0)
                        {
                            int remainder = (int)(intData % 58);
                            intData /= 58;
                            result   = Digits[remainder] + result;
                        }
                        for (int i = 0; i < data123.Length && data123[i] == 0; i++)
                        {
                            result = '1' + result;
                        }
                        csk = result;
                        Console.WriteLine("СГЕНЕРИРОВАН СЕКРЕТНЫЙ КЛЮЧ: " + csk);
                        Console.WriteLine("Установлена сессия с пользователем " + sm.name);
                        RC4Cipher newCipher  = new RC4Cipher(csk, 19);
                        session   newSession = new session()
                        {
                            name = sm.name, cipher = newCipher
                        };

                        addSession(newSession);

                        break;

                    default:
                        string  fp = sm.type.Split('|')[0];
                        string  sp = sm.type.Split('|')[1];
                        session rs = GetSession(sp);
                        if (fp == "message")
                        {
                            Console.WriteLine(sp + "(шифрованное): " + sm.data);
                            string decodemessage = rs.cipher.encode(sm.data);
                            Console.WriteLine(sp + "(дешифрованное): " + decodemessage);
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Подключение прервано! " + e);
                    Console.ReadLine();
                    Disconnect();
                }
            }
        }
예제 #24
0
        private void button4_Click(object sender, EventArgs e)
        {
            Action fileProc = () =>
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                MathNet.Numerics.Control.LinearAlgebraProvider = new MathNet.Numerics.Algorithms.LinearAlgebra.Mkl.MklLinearAlgebraProvider();
                MathNet.Numerics.Control.NumberOfParallelWorkerThreads = Environment.ProcessorCount;
                addText("Обробка файлу вимірювань...\r\n");
                double[][] SGG_data = null;
                if (System.IO.File.Exists("sgg_data.bin"))
                {
                    SGG_data = IOFunc.binLoad_SGG_data("sgg_data.bin");
                }
                else
                {
                    SGG_data = Data.IOFunc.read_SGG_data(SphericalHarmonicAnalyze.Properties.Settings.Default.SGG_measures, new setProgressDel(addVal));
                    IOFunc.binwrite_SGG_data("sgg_data.bin", SGG_data);
                }
                addText("Дані вимірювань оброблено: {0} шт.\r\n", SGG_data.Length); Thread.Sleep(500);
                ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.TideFree);
                elipsoid.gridParameters.cellSize = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize;
                elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude;
                elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder;
                int greedColumnsCount, greedRowsCount;
                List<double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds,180 - elipsoid.gridParameters.coLatitudeBounds);
                addText("Сітку згенеровано: {0} комірок \r\n", greed.Count);
                double avgR = MathFunc.getAvgRadius(SGG_data);
                List<int>[] map = MathFunc.getMappingOfPoints(elipsoid, SGG_data, greed.ToArray(), greedRowsCount, greedColumnsCount, avgR); sw.Stop(); addText("Точки віднесено до комірок сітки за: {0}.\r\n", sw.Elapsed.ToString());
                addText("Кількість клітинок сітки всього: {0}\r\n", greed.Count);
                int res1 = 0; foreach (var item in map) { res1 += item.Count; } addText("Використано вимірів: {0}\r\nСер радіус: {1}\r\n", res1, avgR);
                test.checkMap(SGG_data, map, greed, elipsoid);
                List<int>[] newMap = null;
                MathFunc.checkGreed(ref greed, map, out newMap);
                addText("Кількість клітинок сітки, в яких присутні дані вимірювань: {0}\r\n", greed.Count);
                map = newMap; newMap = null;
                IOFunc.writeGreedToCsvFileWithMeasureCount(greed, map, "greed_new_map.txt");
                double[] avgRadius; sw.Restart();
                double[] regularisedValues = MathFunc.regularization(SGG_data, greed.ToArray(), map, out avgRadius); sw.Stop(); addText("Регуляризація (на основі сферичної відстані) виконана за: {0}.\r\n", sw.Elapsed.ToString());
                IOFunc.writeGreedToCsvFileWithMeasureS(greed,regularisedValues, "greed_regular_grad.txt");
                avgRadius[0] = Math.Round(avgRadius[0]);
                elipsoid.satelliteSphere = avgRadius[0];
                addText("Середній радіус: {0,10:0.000}.\r\nМінімальний радіус: {1,10:0.0000}\r\nМаксимальний радіус:{2,10:0.0000}\r\n", avgRadius[0], avgRadius[1], avgRadius[2]);
                SGG_data = null; map = null;
                int[][] t_nm = MathFunc.get_nm(elipsoid.maxDegree);
                sw.Restart();
                MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(greed.Count, (MathFunc.getArraySize(elipsoid.maxDegree) - 3) * 2 - (elipsoid.maxDegree-1));
                sw.Stop(); addText("Пам'ять для матриці коефіцієнтів виділено за: {0}.\r\n", sw.Elapsed.ToString());
                sw.Restart();
                int progress = 0;
                //Обчислення елементів матриці
                var p= Parallel.For(0, dm.RowCount, (i) =>
                {
                    double[] line = MathFunc.getCoefMatrixLineKoop(elipsoid, elipsoid.maxDegree, t_nm, elipsoid.satelliteSphere, greed[i][0], greed[i][1]);
                    lock (dm)
                    {
                         dm.SetRow(i,line);

                    }
                    progress++;
                    if (progress / 100D == Math.Round(progress / 100D)) {addVal(progress, dm.RowCount, "Визначено");}
                });

                if (!p.IsCompleted) { throw new Exception("Parallel.For"); };
                IOFunc.writeMatrixToMatLabFile(dm, @"matlab\A.mat","A");
                sw.Stop();
                richTextBox1.Invoke(new setProgressDel(addVal), new object[] { 0, dm.RowCount, "" });
                addText("Матриця {0} на {1} ({2}MB) згенерована за: {3,10}\r\n", dm.RowCount, dm.ColumnCount, dm.ColumnCount * dm.RowCount * 8 / 1000000,sw.Elapsed.ToString()/* + "\r\nЗапис у файл...\r\n"*/);
                if(true){
                GravityModel gm08 = new GravityModel(elipsoid.maxDegree);
                gm08.loadFromFile("GO_CONS_EGM_GCF_2.gfc", new setProgressDel(addVal));
                MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm08.getGradientForGrid(elipsoid,greed));//regularisedValues);
                MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL2;
                GravityModel gm = new GravityModel(elipsoid.maxDegree);
                    if (radioButton1.Checked) {
                    sw.Restart();
                    gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
                    sw.Stop(); addText("Вихідна модель завантажена за: {0}.\r\n", sw.Elapsed.ToString());
                    sw.Restart();
                    dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid,greed));
                    sw.Stop(); addText("Градієнти за вихідною моделлю обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                }
                else
                {
                    sw.Restart();
                    gm = GravityModel.getNormalModel(elipsoid, elipsoid.maxDegree);
                    dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed));
                    sw.Stop(); addText("Нормальні градієнти обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                }
                dmL = dmL - dmL2;
                dmL2 = null;
                IOFunc.writeMatrixToMatLabFile(dmL.ToColumnMatrix(), @"matlab\L.mat", "L");
                    sw.Restart();
                MathNet.Numerics.LinearAlgebra.Double.DenseVector dmLNormal = null;
                dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dm.TransposeThisAndMultiply(dmL);
                dmL = null;
                IOFunc.writeMatrixToMatLabFile(dmLNormal.ToColumnMatrix(), @"matlab\LNorm.mat", "LNorm");
                sw.Stop(); addText("Стовпчик вільних членів обчислений за: {0}.\r\n", sw.Elapsed.ToString());
                MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dmANorm = null;
                sw.Restart();
                dmANorm = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)dm.TransposeThisAndMultiply(dm); dm = null;
                sw.Stop(); addText("Нормальна матриця коефіціэнтів обчислена за: {0}.\r\n", sw.Elapsed.ToString());
                IOFunc.writeMatrixToMatLabFile(dmANorm, @"matlab\ANorm.mat", "ANorm");
                //dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dmLNormal.Multiply(5e-8);
                var x = dmANorm.Inverse();
                var res = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)x.Multiply(dmLNormal);
                IOFunc.writeModeVectorlToTxtFile(res, elipsoid, @"matlab\_out.AL");
                addText(@"Результат за методом A\L знайдено...");
                x = null;
                GravityModel gm_R = new GravityModel(gm);
                gm_R.addDeltaCoef(res.ToArray()); res = null;
                double[] h = GravityModel.getGeoidHeight(elipsoid, gm_R, greed);
                double[] dg = GravityModel.getAnomaly(elipsoid, gm_R, greed);
                IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, @"output\result_AL.txt");
                IOFunc.writeGravityModelToTxtFile(gm_R, @"output\model_AL.gcf");
                sw.Restart();
                addText(dmANorm.Rank().ToString() + "\r\n");
                dmANorm = null;
                dmLNormal = null;
                sw.Stop(); addText("Невідомі знайдено за: {0}.\r\n", sw.Elapsed.ToString());

            }
            };

            if (System.IO.File.Exists(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel)) {
            tabControl1.SelectedTab = tabControl1.TabPages[1];
            this.UseWaitCursor = true;
            ts = new CancellationTokenSource();
            ct = ts.Token;
            tsk = Task.Factory.StartNew(fileProc,ct);
            var setCur = Task.Factory.StartNew(() => { tsk.Wait(); this.UseWaitCursor = false; addText("Обчислення завершені!"); });
            richTextBox1.SaveFile(@"output\zvit.rtf");
            }
        }
예제 #25
0
 public static MathNet.Numerics.LinearAlgebra.Double.DenseMatrix readDenceMatrixFromBinFile(string file,MainForm.setProgressDel d)
 {
     string[] meta = System.IO.File.ReadAllLines(file + ".metainfo");
     System.IO.FileStream fs = new System.IO.FileStream(file,System.IO.FileMode.Open);
     System.IO.BinaryReader br = new System.IO.BinaryReader(fs,System.Text.Encoding.Default);
     int cols = int.Parse(meta[1]);
     int rows = int.Parse(meta[3]);
     MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(rows,cols);
     for (int i = 0; i < rows; i++)
     {
         for (int j = 0; j < cols; j++)
         {
             dm[i, j] = br.ReadDouble();
         }
         d.Invoke(br.BaseStream.Position / br.BaseStream.Length, 1, "Завантаження");
     }
     br.Close();
     fs.Close();
     return dm;
 }
예제 #26
0
        public Matrix Inverse()
        {
            if (!IsMatrixQuadratic())
            {
                throw new Exception("Für eine Inverse Matrix muss diese quadratisch sein!");
            }

            //Math.net Library
            MathNetLAGen.Matrix<double> netMatrix = new MathNetLA.Double.DenseMatrix(ToArray());
            var inversedMatrix = new Matrix(netMatrix.Inverse().ToArray());
            return inversedMatrix;
        }
예제 #27
0
        private void CalculateSuperimpositionTransformation_Mathnet(Vector3[] select1, Vector3[] select2,
                                                                    out float[,] rotationMat, out float[] translationMat, out float error)
        {
            int rows        = select1.Length;
            var X           = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(rows, 3);
            var Y           = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(rows, 3);
            var weightArray = new double[rows];

            for (int i = 0; i < rows; i++)
            {
                X[i, 0] = select1[i].X;
                X[i, 1] = select1[i].Y;
                X[i, 2] = select1[i].Z;

                Y[i, 0] = select2[i].X;
                Y[i, 1] = select2[i].Y;
                Y[i, 2] = select2[i].Z;

                if (i <= 11)
                {
                    weightArray[i] = config.weights[i];
                }
                else
                {
                    weightArray[i] = 1;
                }
            }

            var sumColX = X.ColumnSums();
            var mX      = sumColX / rows;
            var sumColY = Y.ColumnSums();
            var mY      = sumColY / rows;

            var mXMatrix = Matrix <double> .Build.DenseOfColumnVectors(mX);

            var mYMatrix = Matrix <double> .Build.DenseOfColumnVectors(mY);

            for (int i = 1; i < rows; i++)
            {
                mXMatrix = mXMatrix.Append(Matrix <double> .Build.DenseOfColumnVectors(mX));
                mYMatrix = mYMatrix.Append(Matrix <double> .Build.DenseOfColumnVectors(mY));
            }

            mXMatrix = mXMatrix.Transpose();
            mYMatrix = mYMatrix.Transpose();
            var X0 = X - mXMatrix;
            var Y0 = Y - mYMatrix;

            var normX = X0.FrobeniusNorm();
            var normY = Y0.FrobeniusNorm();

            var W = Matrix <double> .Build.DiagonalOfDiagonalArray(weightArray);

            var A   = X0.Transpose() * W * W * Y0;
            var svd = A.Svd(true); // U, VT

            var L       = svd.U;
            var D       = svd.W;
            var MT      = svd.VT;
            var T       = (L * MT).ConjugateTranspose();
            var traceTA = D.Diagonal().Sum();

            var e = 1 + Math.Pow((normY / normX), 2) - 2 * traceTA * normY / normX;
            var c = mX - mY * T;

            error          = (float)e;
            translationMat = c.Map(x => (float)x).ToArray();
            rotationMat    = (T.Map(x => (float)x)).ToArray();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        /// <param name="q"></param>
        /// <returns></returns>
        public static Matrix3D Rigid3D(IList<Vector3D> p, IList<Vector3D> q)
        {
            int n = p.Count;
            double[] m = new double[9];
            for (int i = 0; i < n; i++)
            {
                m[0] += p[i].X * q[i].X;
                m[1] += p[i].X * q[i].Y;
                m[2] += p[i].X * q[i].Z;
                m[3] += p[i].Y * q[i].X;
                m[4] += p[i].Y * q[i].Y;
                m[5] += p[i].Y * q[i].Z;
                m[6] += p[i].Z * q[i].X;
                m[7] += p[i].Z * q[i].Y;
                m[8] += p[i].Z * q[i].Z;
            }

            var M = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(3, 3, m);
            //double[] S = new double[3];
            //double[] U = new double[9];
            //double[] VT = new double[9];
            //mklSolver.SingularValueDecomposition(true, M.Data, 3, 3, S, U, VT);
            //var RR = new Matrix3D()
            //{
            //    M11 = U[0] * VT[0] + U[1] * VT[3] * U[2] * VT[6],
            //    M12 = U[0] * VT[1] + U[1] * VT[4] * U[2] * VT[7],
            //    M13 = U[0] * VT[2] + U[1] * VT[5] * U[2] * VT[8],

            //    M21 = U[3] * VT[0] + U[4] * VT[3] * U[5] * VT[6],
            //    M22 = U[3] * VT[1] + U[4] * VT[4] * U[5] * VT[7],
            //    M23 = U[3] * VT[2] + U[4] * VT[5] * U[5] * VT[8],

            //    M31 = U[6] * VT[0] + U[7] * VT[3] * U[8] * VT[6],
            //    M32 = U[6] * VT[1] + U[7] * VT[4] * U[8] * VT[7],
            //    M33 = U[6] * VT[2] + U[7] * VT[5] * U[8] * VT[8],
            //};
            //return RR;

            // R = V*UT <==> RT = VT*U
            var svd = M.Svd(true);
            var RT = svd.U().Multiply(svd.VT());
            var R = new Matrix3D()
            {
                M11 = RT[0, 0],
                M12 = RT[1, 0],
                M13 = RT[2, 0],
                M21 = RT[0, 1],
                M22 = RT[1, 1],
                M23 = RT[2, 1],
                M31 = RT[0, 2],
                M32 = RT[1, 2],
                M33 = RT[2, 2],
                //M11 = RT[0, 0],
                //M12 = RT[0, 1],
                //M13 = RT[0, 2],
                //M21 = RT[1, 0],
                //M22 = RT[1, 1],
                //M23 = RT[1, 2],
                //M31 = RT[2, 0],
                //M32 = RT[2, 1],
                //M33 = RT[2, 2],
                M44 = 1.0,
            };

            return R;
        } 
예제 #29
0
        public void ConeGestureFinished()
        {
            ConeGestureInProgress = false;

            GetComponent <LineRenderer>().enabled = false;

            // Process cone gesture data here
            // Start by converting (local) XYZ to TNB coordinates w.r.t the curve
            var startIdx = coneGesturePositionData.Count / 10;
            var endIdx   = coneGesturePositionData.Count * 9 / 10;
            var n        = endIdx - startIdx;

            double[] posData = new double[3 * n];
            double[] velData = new double[3 * n];
            double[] accData = new double[3 * n];

            for (int i = startIdx; i < endIdx; ++i)
            {
                var pos = coneGesturePositionData[i];
                var vel = coneGestureVelocityData[i];
                var acc = coneGestureAccelerationData[i];
                emissionCurve.GetClosestPoint(pos, out Vector3 closest, out int bezierIdx, out float param);
                var tangent  = emissionCurve.Tangent(bezierIdx, param);
                var normal   = emissionCurve.Normal(bezierIdx, param);
                var binormal = Vector3.Cross(tangent, normal);
                var delta    = (pos - closest);
                var time     = emissionCurve.GetTimeFromSplineParam(bezierIdx, param);

                // For points, first coordinate is time, and the other two given by dot product
                pos = new Vector3(time, Vector3.Dot(delta, normal), Vector3.Dot(delta, binormal));

                // For vectors, all three coordinates given by projecting to the new frame (dot product)
                vel = new Vector3(Vector3.Dot(vel, tangent), Vector3.Dot(vel, normal), Vector3.Dot(vel, binormal));
                acc = new Vector3(Vector3.Dot(acc, tangent), Vector3.Dot(acc, normal), Vector3.Dot(acc, binormal));

                for (var j = 0; j < 3; ++j)
                {
                    var idx = n * j + i - startIdx;
                    posData[idx] = pos[j];
                    velData[idx] = vel[j];
                    accData[idx] = acc[j];
                }
            }

            // Perform SVD to get principal components
            Matrix <double> P = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(n, 3, posData);
            Matrix <double> V = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(n, 3, velData);
            Matrix <double> A = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(n, 3, accData);

            var accSvd = A.Svd(true);

            var SA = accSvd.S;
            var VA = accSvd.VT;

            if (SA[0] / SA[1] > Globals.CONE_GESTURE_CLASSIFICATION_SINGULAR_VALUE_RATIO)
            {
                ProcessEmissionNoiseGesture(P, VA);
            }
            else
            {
                ProcessSpiralForceGesture(P, V);
            }

            Debug.Log("Delsecting because cone gesture finished");
            animScript.Deselected();
        }