/// <summary>
        /// Initializes a new instance of the <see cref="DenseEvd"/> class. This object will compute the
        /// the eigenvalue decomposition when the constructor is called and cache it's decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If EVD algorithm failed to converge with matrix <paramref name="matrix"/>.</exception>
        public DenseEvd(DenseMatrix matrix)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare);
            }

            var order = matrix.RowCount;

            // Initialize matrices for eigenvalues and eigenvectors
            MatrixEv = DenseMatrix.Identity(order);
            MatrixD = matrix.CreateMatrix(order, order);
            VectorEv = new Complex.DenseVector(order);

            IsSymmetric = true;

            for (var i = 0; IsSymmetric && i < order; i++)
            {
                for (var j = 0; IsSymmetric && j < order; j++)
                {
                    IsSymmetric &= matrix.At(i, j) == matrix.At(j, i).Conjugate();
                }
            }

            Control.LinearAlgebraProvider.EigenDecomp(IsSymmetric, order, matrix.Values, ((DenseMatrix) MatrixEv).Values,
                ((Complex.DenseVector) VectorEv).Values, ((DenseMatrix) MatrixD).Values);
        }
Example #2
0
 public static void Main(string[] args)
 {
   using (Model M  = new Model("sdo1"))
   {
     // Setting up the variables
     Variable X  = M.Variable("X", Domain.InPSDCone(3));
     Variable x  = M.Variable("x", Domain.InQCone(3));
     
     DenseMatrix C  = new DenseMatrix ( new double[][] { new double[] {2,1,0}, new double[] {1,2,1}, new double[] {0,1,2}} );
     DenseMatrix A1 = new DenseMatrix ( new double[][] { new double[] {1,0,0}, new double[] {0,1,0}, new double[] {0,0,1}} );
     DenseMatrix A2 = new DenseMatrix ( new double[][] { new double[] {1,1,1}, new double[] {1,1,1}, new double[] {1,1,1}} );
     
     // Objective
     M.Objective(ObjectiveSense.Minimize, Expr.Add(Expr.Dot(C, X), x.Index(0)));
     
     // Constraints
     M.Constraint("c1", Expr.Add(Expr.Dot(A1, X), x.Index(0)), Domain.EqualsTo(1.0));
     M.Constraint("c2", Expr.Add(Expr.Dot(A2, X), Expr.Sum(x.Slice(1,3))), Domain.EqualsTo(0.5));
     
     M.Solve();
     
     Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(X.Level()).ToString());
     Console.WriteLine("[{0}]", (new Utils.StringBuffer()).A(x.Level()).ToString());
   }
 }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseEvd"/> class. This object will compute the
        /// the eigenvalue decomposition when the constructor is called and cache it's decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If EVD algorithm failed to converge with matrix <paramref name="matrix"/>.</exception>
        public static DenseEvd Create(DenseMatrix matrix)
        {
            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare);
            }

            var order = matrix.RowCount;

            // Initialize matrices for eigenvalues and eigenvectors
            var eigenVectors = DenseMatrix.Identity(order);
            var blockDiagonal = new DenseMatrix(order);
            var eigenValues = new DenseVector(order);

            var isSymmetric = true;

            for (var i = 0; isSymmetric && i < order; i++)
            {
                for (var j = 0; isSymmetric && j < order; j++)
                {
                    isSymmetric &= matrix.At(i, j) == matrix.At(j, i).Conjugate();
                }
            }

            Control.LinearAlgebraProvider.EigenDecomp(isSymmetric, order, matrix.Values, eigenVectors.Values, eigenValues.Values, blockDiagonal.Values);

            return new DenseEvd(eigenVectors, eigenValues, blockDiagonal, isSymmetric);
        }
Example #4
0
        public bool ReadFile(string fileName)
        {
            TextReader tr = null;
            try {
                tr = new StreamReader(fileName);
            } catch (Exception e) {
                return false;
            }

            string buffer = tr.ReadLine();
            string[] numbers = buffer.Split(' ');

            N = int.Parse(numbers[0]);
            P = int.Parse(numbers[1]);

            A = new DenseMatrix(P, N);
            for (int i = 0; i < P; i++) {
                buffer = tr.ReadLine();
                numbers = buffer.Split(' ');
                for (int j = 0; j < N; j++) {
                    A[i,j] = int.Parse(numbers[j]);
                }
            }
            B = new DenseVector(P);
            for (int i = 0; i < P; i++) {
                buffer = tr.ReadLine();
                B[i] = int.Parse(buffer);
            }

            return true;
        }
Example #5
0
        public DenseMatrix Simulate(DenseMatrix inputs) //rows: t, cols: inputcount
        {
            states = new Vector(states.Elements.Length);

            DenseMatrix temp = inputs.MatrixMultiply(inputWeights);

            DenseMatrix ret = new DenseMatrix(inputs.Rows, states.Elements.Length);

            for (int t = 0; t < temp.Rows; ++t)
            {
                Vector v = temp.GetRow(t);                
                Vector states2 = innerConnections.MatrixMultiplyRight(states);
                states2.Add(v);
                states2.Add(biasWeights);
                for (int i = 0; i < states2.Elements.Length; ++i)
                {
                    states2.Elements[i] = (double)Math.Tanh(states2.Elements[i]);
                }

                states = states2;
                for (int i = 0; i < states.Elements.Length; ++i)
                {
                    ret[t, i] = states.Elements[i];
                }
            }

            return ret;
        }
Example #6
0
        // Computes coefficients of real polynomial (or estimates if values are noised) using Svd
        // Each row of matrix should contain [x, P(x)], at least rank+1 rows
        // Supplied x-es best have magintude in range [1-2], so resulting coefficient matrix is well conditioned
        public static Polynomial EstimatePolynomial(Matrix<float> values, int rank)
        {
            // 1) Create equation Xa = b
            // | x1^n x1^n-1 ... x1 1 | | a0 |   | P(x1) |
            // |                      | | ...| = |       |
            // | xk^n xk^n-1 ... xk 1 | | an |   | P(xk) |
            Matrix<float> X = new DenseMatrix(values.RowCount, rank + 1);
            Vector<float> P = new DenseVector(values.RowCount);

            for(int i = 0; i < values.RowCount; ++i)
            {
                X[i, rank] = 1.0f;
                for(int c = rank - 1; c >= 0; --c)
                {
                    X[i, c] = X[i, c + 1] * values.At(i, 0);
                }
                P[i] = values[i, 1];
            }

            return new Polynomial()
            {
                Coefficents = SvdSolver.Solve(X, P),
                Rank = rank
            };
        }
 public void MatrixFrom1DArrayIsReference()
 {
     var data = new double[] { 1, 1, 1, 1, 1, 1, 2, 2, 2 };
     var matrix = new DenseMatrix(3, 3, data);
     matrix[0, 0] = 10.0;
     Assert.AreEqual(10.0, data[0]);
 }
        public void ValidateMatrixFactoryParse()
        {
            denseMatObj = GetDenseMatrix();

            MatrixFactory<String, String, Double> mfObj =
                MatrixFactory<String, String, Double>.GetInstance();

            ParallelOptions poObj = new ParallelOptions();

            TryParseMatrixDelegate<string, string, double> a =
                new TryParseMatrixDelegate<string, string, double>(this.TryParseMatrix);
            mfObj.RegisterMatrixParser(a);
            // Writes the text file
            denseMatObj.WritePaddedDouble(Constants.FastQTempTxtFileName, poObj);

            Matrix<string, string, double> newMatObj =
                mfObj.Parse(Constants.FastQTempTxtFileName, double.NaN, poObj);

            Assert.AreEqual(denseMatObj.RowCount, newMatObj.RowCount);
            Assert.AreEqual(denseMatObj.RowKeys.Count, newMatObj.RowKeys.Count);
            Assert.AreEqual(denseMatObj.ColCount, newMatObj.ColCount);
            Assert.AreEqual(denseMatObj.ColKeys.Count, newMatObj.ColKeys.Count);
            Assert.AreEqual(denseMatObj.Values.Count(), newMatObj.Values.Count());

            ApplicationLog.WriteLine(
                "MatrixFactory BVT : Successfully validated Parse() method");
        }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseQR"/> class. This object will compute the
        /// QR factorization when the constructor is called and cache it's factorization.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="method">The QR factorization method to use.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="matrix"/> row count is less then column count</exception>
        public static DenseQR Create(DenseMatrix matrix, QRMethod method = QRMethod.Full)
        {
            if (matrix.RowCount < matrix.ColumnCount)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(matrix);
            }

            var tau = new float[Math.Min(matrix.RowCount, matrix.ColumnCount)];
            Matrix<float> q;
            Matrix<float> r;

            if (method == QRMethod.Full)
            {
                r = matrix.Clone();
                q = new DenseMatrix(matrix.RowCount);
                Control.LinearAlgebraProvider.QRFactor(((DenseMatrix) r).Values, matrix.RowCount, matrix.ColumnCount, ((DenseMatrix) q).Values, tau);
            }
            else
            {
                q = matrix.Clone();
                r = new DenseMatrix(matrix.ColumnCount);
                Control.LinearAlgebraProvider.ThinQRFactor(((DenseMatrix) q).Values, matrix.RowCount, matrix.ColumnCount, ((DenseMatrix) r).Values, tau);
            }

            return new DenseQR(q, r, method, tau);
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseEvd"/> class. This object will compute the
        /// the eigenvalue decomposition when the constructor is called and cache it's decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="symmetricity">If it is known whether the matrix is symmetric or not the routine can skip checking it itself.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If EVD algorithm failed to converge with matrix <paramref name="matrix"/>.</exception>
        public static DenseEvd Create(DenseMatrix matrix, Symmetricity symmetricity)
        {
            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare);
            }

            var order = matrix.RowCount;

            // Initialize matrices for eigenvalues and eigenvectors
            var eigenVectors = new DenseMatrix(order);
            var blockDiagonal = new DenseMatrix(order);
            var eigenValues = new LinearAlgebra.Complex.DenseVector(order);

            bool isSymmetric;
            switch (symmetricity)
            {
                case Symmetricity.Symmetric:
                case Symmetricity.Hermitian:
                    isSymmetric = true;
                    break;
                case Symmetricity.Asymmetric:
                    isSymmetric = false;
                    break;
                default:
                    isSymmetric = matrix.IsSymmetric();
                    break;
            }

            Control.LinearAlgebraProvider.EigenDecomp(isSymmetric, order, matrix.Values, eigenVectors.Values, eigenValues.Values, blockDiagonal.Values);

            return new DenseEvd(eigenVectors, eigenValues, blockDiagonal, isSymmetric);
        }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseQR"/> class. This object will compute the
        /// QR factorization when the constructor is called and cache it's factorization.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="method">The QR factorization method to use.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="matrix"/> row count is less then column count</exception>
        public DenseQR(DenseMatrix matrix, QRMethod method = QRMethod.Full)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if (matrix.RowCount < matrix.ColumnCount)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(matrix);
            }

            Tau = new Complex32[Math.Min(matrix.RowCount, matrix.ColumnCount)];

            if (method == QRMethod.Full)
            {
                MatrixR = matrix.Clone();
                MatrixQ = new DenseMatrix(matrix.RowCount);
                Control.LinearAlgebraProvider.QRFactor(((DenseMatrix)MatrixR).Values, matrix.RowCount, matrix.ColumnCount,
                                                       ((DenseMatrix)MatrixQ).Values, Tau);
            }
            else
            {
                MatrixQ = matrix.Clone();
                MatrixR = new DenseMatrix(matrix.ColumnCount);
                Control.LinearAlgebraProvider.ThinQRFactor(((DenseMatrix)MatrixQ).Values, matrix.RowCount, matrix.ColumnCount,
                                                       ((DenseMatrix)MatrixR).Values, Tau);
            }
        }
Example #12
0
        public static void Main()
        {
            Matrix matrix = new DenseMatrix(5, 6);
            for (int i = 0; i < matrix.Rows; i++)
            {
                for (int j = 0; j < matrix.Columns; j++)
                {
                    matrix[i, j] = j;
                }
            }

            //the enumerator returns a KeyValuePair, where the key is the column number
            //and the value is the column as a Vector.
            foreach (KeyValuePair<int, Vector> column in matrix.GetColumnEnumerator())
            {
                Console.WriteLine("Column: {0}", column.Key);

                //the Vector enumerator also returns a KeyValuePair with the key
                //being the element's position in the Vector (the row in this case)
                //and the value being the element's value.
                foreach (double element in column.Value)
                {
                    Console.WriteLine(element);
                }
            }
        }
Example #13
0
 public static void Main(string[] args)
 {
   Matrix recipe = new DenseMatrix(recipe_data);
   using (Model M = new Model("Recipe"))
   {
     // "production" defines the amount of each product to bake.
     Variable production = M.Variable("production", 
                                      new StringSet(productnames), 
                                      Domain.GreaterThan(0.0));
     // The objective is to maximize the total revenue.
     M.Objective("revenue",
                 ObjectiveSense.Maximize, 
                 Expr.Dot(revenue, production));
     
     // The prodoction is constrained by stock:
     M.Constraint(Expr.Mul(recipe, production), Domain.LessThan(stock));
     M.SetLogHandler(Console.Out);
   
     // We solve and fetch the solution:
     M.Solve();
     double[] res = production.Level();
     Console.WriteLine("Solution:");
     for (int i = 0; i < res.Length; ++i)
     {
       Console.WriteLine(" Number of {0} : {1}", productnames[i], res[i]);
     }
     Console.WriteLine(" Revenue : ${0}", 
                       res[0] * revenue[0] + res[1] * revenue[1]);
   }
 }
Example #14
0
        public void Train(DenseMatrix states, DenseMatrix targets)
        {
            //hogy lehetne ugy tanitani, LS modszerrel, hogy ne vesszen el a mar beletanitott cucc
            //hogy lehetne megjegyezni, hogy mi az amit mar megtanitottunk neki
            //valoszinusegi jelentest hogy lehetne adni ennek a dolognak... 
            //valami matrixot karbantartva, ami megmondja, hogy mekkora a szorasa/informaciotartalma az adott helyen

        }
 public void WriteNullMatricesThrowsArgumentNullException()
 {
     var writer = new MatlabMatrixWriter("somefile4");
     Assert.Throws<ArgumentNullException>(() => writer.WriteMatrices(new Matrix[] { null }, new[] { "matrix" }));
     Matrix matrix = new DenseMatrix(1, 1);
     Assert.Throws<ArgumentNullException>(() => writer.WriteMatrices(new[] { matrix }, null));
     writer.Dispose();
 }
Example #16
0
 public Transformation()
 {
     iMatrix = new DenseMatrix(3);
     for (int i = 0; i < 3; i++)
     {
         iMatrix[i, i] = 1.0;
     }
 }
Example #17
0
 public static DenseMatrix FilterColumnsBy(this Matrix m, int[] filter)
 {
     var result = new DenseMatrix(m.Rows, filter.Length);
     for (int j = 0; j < filter.Length; ++j) {
         result.SetColumn(j, m.GetColumn(j));
     }
     return result;
 }
Example #18
0
 public static DenseMatrix FilterRowsBy(this Matrix m, int[] filter)
 {
     var result = new DenseMatrix(filter.Length, m.Columns);
     for (int i = 0; i < filter.Length; ++i) {
         result.SetRow(i, m.GetRow(filter[i]));
     }
     return result;
 }
Example #19
0
 public MarkowitzData(string name)
 {      
   n      = Int32.Parse(File.ReadAllText(name+"-n.txt"));
   gammas = readfile(name + "-gammas.csv");
   mu     = readfile(name + "-mu.csv");
   GT     = new DenseMatrix(readlines(name + "-GT.csv"));
   x0     = readfile(name + "-x0.csv");
   w      = Double.Parse(File.ReadAllText(name+"-w.csv"));
 }
Example #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseEvd"/> class. This object will compute the
        /// the eigenvalue decomposition when the constructor is called and cache it's decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If EVD algorithm failed to converge with matrix <paramref name="matrix"/>.</exception>
        public DenseEvd(DenseMatrix matrix)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare);
            }

            var order = matrix.RowCount;

            // Initialize matricies for eigenvalues and eigenvectors
            MatrixEv = DenseMatrix.Identity(order);
            MatrixD = matrix.CreateMatrix(order, order);
            VectorEv = new LinearAlgebra.Complex.DenseVector(order);

            IsSymmetric = true;

            for (var i = 0; i < order & IsSymmetric; i++)
            {
                for (var j = 0; j < order & IsSymmetric; j++)
                {
                    IsSymmetric &= matrix[i, j] == matrix[j, i].Conjugate();
                }
            }

            if (IsSymmetric)
            {
                var matrixCopy = matrix.ToArray();
                var tau = new Complex32[order];
                var d = new float[order];
                var e = new float[order];

                SymmetricTridiagonalize(matrixCopy, d, e, tau, order);
                SymmetricDiagonalize(((DenseMatrix)MatrixEv).Data, d, e, order);
                SymmetricUntridiagonalize(((DenseMatrix)MatrixEv).Data, matrixCopy, tau, order);

                for (var i = 0; i < order; i++)
                {
                    VectorEv[i] = new Complex(d[i], e[i]);
                }
            }
            else
            {
                var matrixH = matrix.ToArray();
                NonsymmetricReduceToHessenberg(((DenseMatrix)MatrixEv).Data, matrixH, order);
                NonsymmetricReduceHessenberToRealSchur(((LinearAlgebra.Complex.DenseVector)VectorEv).Data, ((DenseMatrix)MatrixEv).Data, matrixH, order);
            }

            for (var i = 0; i < VectorEv.Count; i++)
            {
                MatrixD.At(i, i, (Complex32)VectorEv[i]);
            }
        }
Example #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseSvd"/> class. This object will compute the
        /// the singular value decomposition when the constructor is called and cache it's decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="computeVectors">Compute the singular U and VT vectors or not.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If SVD algorithm failed to converge with matrix <paramref name="matrix"/>.</exception>
        public static DenseSvd Create(DenseMatrix matrix, bool computeVectors)
        {
            var nm = Math.Min(matrix.RowCount, matrix.ColumnCount);
            var s = new DenseVector(nm);
            var u = new DenseMatrix(matrix.RowCount);
            var vt = new DenseMatrix(matrix.ColumnCount);
            Control.LinearAlgebraProvider.SingularValueDecomposition(computeVectors, ((DenseMatrix) matrix.Clone()).Values, matrix.RowCount, matrix.ColumnCount, s.Values, u.Values, vt.Values);

            return new DenseSvd(s, u, vt, computeVectors);
        }
        public void CanComputeDeterminant()
        {
            var matrix = TestMatrices["Square3x3"];
            var denseMatrix = new DenseMatrix(TestData2D["Square3x3"]);
            AssertHelpers.AlmostEqual(denseMatrix.Determinant(), matrix.Determinant(), 14);

            matrix = TestMatrices["Square4x4"];
            denseMatrix = new DenseMatrix(TestData2D["Square4x4"]);
            AssertHelpers.AlmostEqual(denseMatrix.Determinant(), matrix.Determinant(), 14);
        }
 public void WriteBadMatricesThrowsArgumentException()
 {
     Matrix matrix = new DenseMatrix(1, 1);
     var writer = new MatlabMatrixWriter("somefile3");
     Assert.Throws<ArgumentException>(() => writer.WriteMatrices(new[] { matrix }, new[] { string.Empty }));
     Assert.Throws<ArgumentException>(() => writer.WriteMatrices(new[] { matrix }, new string[] { null }));
     Assert.Throws<ArgumentException>(() => writer.WriteMatrices(new[] { matrix, matrix }, new[] { "matrix" }));
     Assert.Throws<ArgumentException>(() => writer.WriteMatrices(new[] { matrix }, new[] { "some matrix" }));
     writer.Dispose();
 }
Example #24
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var dm = new DenseMatrix(10, 10);
            Console.WriteLine(dm.Get(5, 5));

            Console.WriteLine("Score test:");
            Test();
        }
 public void CanCreateMatrixFrom2DArray([Values("Singular3x3", "Singular4x4", "Square3x3", "Square4x4", "Tall3x2", "Wide2x3")] string name)
 {
     var matrix = new DenseMatrix(TestData2D[name]);
     for (var i = 0; i < TestData2D[name].GetLength(0); i++)
     {
         for (var j = 0; j < TestData2D[name].GetLength(1); j++)
         {
             Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]);
         }
     }
 }
 public void CanCreateMatrixFrom2DArray(string name)
 {
     var matrix = new DenseMatrix(testData2D[name]);
     for (var i = 0; i < testData2D[name].GetLength(0); i++)
     {
         for (var j = 0; j < testData2D[name].GetLength(1); j++)
         {
             Assert.AreEqual(testData2D[name][i, j], matrix[i, j]);
         }
     }
 }
 public void CanCreateMatrixWithUniformValues()
 {
     var matrix = new DenseMatrix(10, 10, 10.0);
     for (var i = 0; i < matrix.RowCount; i++)
     {
         for (var j = 0; j < matrix.ColumnCount; j++)
         {
             Assert.AreEqual(matrix[i, j], 10.0);
         }
     }
 }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DenseCholesky"/> class. This object will compute the
        /// Cholesky factorization when the constructor is called and cache it's factorization.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception>
        /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not positive definite.</exception>
        public static DenseCholesky Create(DenseMatrix matrix)
        {
            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare);
            }

            // Create a new matrix for the Cholesky factor, then perform factorization (while overwriting).
            var factor = (DenseMatrix) matrix.Clone();
            Control.LinearAlgebraProvider.CholeskyFactor(factor.Values, factor.RowCount);
            return new DenseCholesky(factor);
        }
Example #29
0
 public static void CreateGrid(int N1, int N2, out Matrix x, out Matrix y)
 {
     int M = N1 * N2;
     x = new DenseMatrix(M, 1);
     y = new DenseMatrix(M, 1);
     for (int i = 0; i < N2; ++i) {
         for (int j = 0; j < N1; ++j) {
             x[i * N1 + j, 0] = i;
             y[i * N1 + j, 0] = j;
         }
     }
 }
        public void CanWriteMatrices()
        {
            Matrix mat1 = new DenseMatrix(5, 3);
            for (var i = 0; i < mat1.ColumnCount; i++)
            {
                mat1[i, i] = new Complex32(i + .1f, i + .1f);
            }

            Matrix mat2 = new DenseMatrix(4, 5);
            for (var i = 0; i < mat2.RowCount; i++)
            {
                mat2[i, i] = new Complex32(i + .1f, i + .1f);
            }

            Matrix mat3 = new SparseMatrix(5, 4);
            for (var i = 0; i < mat3.ColumnCount; i++)
            {
                mat3[i, i] = new Complex32(i + .1f, i + .1f);
            }

            Matrix mat4 = new SparseMatrix(3, 5);
            for (var i = 0; i < mat4.RowCount; i++)
            {
                mat4[i, i] = new Complex32(i + .1f, i + .1f);
            }

            var write = new[] { mat1, mat2, mat3, mat4 };

            var names = new[] { "mat1", "dense_matrix_2", "s1", "sparse2" };
            if (File.Exists("test.mat"))
            {
                File.Delete("test.mat");
            }

            var writer = new MatlabMatrixWriter("test.mat");
            writer.WriteMatrices(write, names);
            writer.Dispose();

            var reader = new MatlabMatrixReader("test.mat");
            var read = reader.ReadMatrices(names);

            Assert.AreEqual(write.Length, read.Count);

            for (var i = 0; i < write.Length; i++)
            {
                var w = write[i];
                var r = read[names[i]];

                Assert.AreEqual(w.RowCount, r.RowCount);
                Assert.AreEqual(w.ColumnCount, r.ColumnCount);
                Assert.IsTrue(w.Equals(r));
            }
        }
 /// <summary>
 /// Creates a matrix from a 2D array.
 /// </summary>
 /// <param name="data">The 2D array to create this matrix from.</param>
 /// <returns>A matrix with the given values.</returns>
 protected override Matrix <float> CreateMatrix(float[,] data)
 {
     return(DenseMatrix.OfArray(data));
 }
Example #32
0
 /// <summary>
 /// Computes the determinant of a matrix.
 /// </summary>
 /// <param name="matrix">a matrix</param>
 public static double Determinant(DenseMatrix matrix)
 {
     return(matrix.Determinant());
 }
        public Matrix XYZConverter()
        {
            Vector <double> SrSgSb = GetSrSgSb();

            return(DenseMatrix.OfColumnVectors(RedVector * SrSgSb[0], GreenVector * SrSgSb[1], BlueVector * SrSgSb[2]));
        }
Example #34
0
        protected virtual void TestRandomMulti(SparseMatrix matrix)
        {
            Console.Write("Testing {0} (multi) ... ", name);

            var A = (SparseMatrix)matrix.Clone();

            int count = 3;

            int n = A.RowCount;

            var b = Vector.Create(n, 0.0);
            var x = Vector.Create(n, 0.0);
            var s = Vector.Create(n, 0.0);

            var X = new DenseMatrix(n, count);
            var S = new DenseMatrix(n, count);
            var B = new DenseMatrix(n, count);

            for (int i = 0; i < count; i++)
            {
                x = Vector.Create(n, i + 1);

                X.SetColumn(i, x);
                S.SetColumn(i, x);

                A.Multiply(x, b);

                B.SetColumn(i, b);
            }

            X.Clear();

            try
            {
                timer.Restart();

                using (var solver = CreateSolver(A, false))
                {
                    //solver.Solve(B, X);
                }

                timer.Stop();

                Display.Time(timer.ElapsedTicks);

                double error = 0.0;

                for (int i = 0; i < count; i++)
                {
                    X.Column(i, x);
                    S.Column(i, s);

                    error += Helper.ComputeError(x, s);
                }

                if (error / count > ERROR_THRESHOLD)
                {
                    Display.Warning("relative error too large");
                }
                else
                {
                    Display.Ok("OK");
                }
            }
            catch (DllNotFoundException)
            {
                throw;
            }
            catch (Exception e)
            {
                Display.Error(e.Message);
            }
        }
 // Define a Identity matrix
 public void Identity3DHomegeneous()
 {
     this.Matrix = DenseMatrix.CreateIdentity(4);
 }
Example #36
0
 /// <summary>
 /// Computes the inverse of a matrix.
 /// </summary>
 /// <param name="matrix">a matrix</param>
 public static DenseMatrix Inverse(DenseMatrix matrix)
 {
     return(DenseMatrix.OfMatrix(matrix.Inverse()));
 }
Example #37
0
        public static void FillMatrices()
        {
            // 1. Fill G Matrix
            G = new DenseMatrix(N, N);
            for (var i = 0; i < N; i++)
            {
                for (var j = 0; j < N; j++)
                {
                    if (i == j)
                    {
                        foreach (var resistance in Nodes[(i + 1).ToString()].Resistances)
                        {
                            if (resistance[0] == 'R')
                            {
                                G[i, j] += 1 / ComponentsValues[resistance];
                            }
                            else if (resistance[0] == 'C')
                            {
                                G[i, j] += ComponentsValues[resistance] / H;
                            }
                        }
                    }
                    else
                    {
                        var nr1 = Nodes[(i + 1).ToString()].Resistances;
                        var nr2 = Nodes[(j + 1).ToString()].Resistances;
                        var ir  = nr1.Intersect(nr2).ToList();
                        foreach (var resistance in ir)
                        {
                            if (resistance[0] == 'R')
                            {
                                G[i, j] += -1 / ComponentsValues[resistance];
                            }
                            else if (resistance[0] == 'C')
                            {
                                G[i, j] += -ComponentsValues[resistance] / H;
                            }
                        }
                    }
                }
            }

            // 2. Fill Matrix B
            B = new DenseMatrix(N, M + L);
            for (var i = 0; i < N; i++)
            {
                var    vl = Nodes[(i + 1).ToString()].VoltageSources;
                int    co = 1;
                string rq = "Vsrc";
                for (var j = 0; j < M + L; j++)
                {
                    if (j == M)
                    {
                        co = 1;
                        rq = "I";
                    }
                    var vsrc = vl.Find(e => e.Contains(rq + co));
                    if (vsrc != null)
                    {
                        if (vsrc[0] == '+')
                        {
                            B[i, j] = 1;
                        }
                        else if (vsrc[0] == '-')
                        {
                            B[i, j] = -1;
                        }
                    }
                    else
                    {
                        B[i, j] = 0;
                    }
                    co++;
                }
            }

            // 3. Fill Matrix C
            C = B.Transpose() as DenseMatrix;

            // 4. Fill Matrix D
            D = new DenseMatrix(M + L, M + L);
            if (L > 0)
            {
                for (int i = 0; i < M + L; i++)
                {
                    if (i >= M)
                    {
                        D[i, i] = -ComponentsValues["I" + i] / H;
                    }
                }
            }

            // 5. Combine to form Matrix A
            A = new DenseMatrix(M + N + L, M + N + L);
            int r = 0;

            for (var i = 0; i < M + N + L; i++)
            {
                int c = 0;
                for (var j = 0; j < M + N + L; j++)
                {
                    if (i < N)
                    {
                        if (j < N)
                        {
                            A[i, j] = G[i, j];
                        }
                        else
                        {
                            A[i, j] = B[i, c++];
                        }
                        r = 0; //HACK
                    }
                    else
                    {
                        if (j < N)
                        {
                            if (C != null)
                            {
                                A[i, j] = C[r - 1, j];
                            }
                        }
                        else
                        {
                            A[i, j] = D[r - 1, c++];
                        }
                    }
                }
                r++;
            }

            //6. Fill Vector Z
            FillMatrixZ();
        }
        public void getparameters()
        {
            double[] patientid = PatientIDs.ToArray();
            //MessageBox.Show(patientid.Length.ToString() + " yo");
            string[] mednames = Medications.ToArray();
            mother.Open();//starts here
            for (int o = 0; o < mednames.Length; o++)
            {
                DataRow maboi = datatab.NewRow();
                maboi["Medication"] = mednames[o];
                for (int y = 0; y < patientid.Length; y++)
                {
                    string        getsesnums = "SELECT * FROM Session_Table WHERE Medication='" + mednames[o] + "' AND ID=" + patientid[y] + " ORDER BY Date";
                    SqlCommand    pointcom   = new SqlCommand(getsesnums, mother);
                    SqlDataReader pointread  = pointcom.ExecuteReader();
                    while (pointread.Read())
                    {
                        UsedAmounts.Add(Convert.ToDouble(Convert.ToDouble(pointread["Used_Amount"])));
                    }
                    pointread.Close(); // SHIFTY STUFF, IS IT PROPER?
                }

                for (int hu = 0; hu < 6; hu++)
                {
                    if (hu == 0)
                    {
                        UsedAmount.Clear();
                        SessionNumber.Clear();
                        Attribute.Clear();
                        indicate = "Sleep Quality";
                        fillthearray(mednames[o], "Quality_of_Sleep");
                    }
                    if (hu == 1)
                    {
                        UsedAmount.Clear();
                        SessionNumber.Clear();
                        Attribute.Clear();
                        indicate = "Appetite";
                        fillthearray(mednames[o], "Appetite");
                    }
                    if (hu == 2)
                    {
                        UsedAmount.Clear();
                        SessionNumber.Clear();
                        Attribute.Clear();
                        indicate = "Eye Contact";
                        fillthearray(mednames[o], "Eye_Contact");
                    }
                    if (hu == 3)
                    {
                        UsedAmount.Clear();
                        SessionNumber.Clear();
                        Attribute.Clear();
                        indicate = "Voice Tone";
                        fillthearray(mednames[o], "Voice_Tone_Consistency");
                    }
                    if (hu == 4)
                    {
                        UsedAmount.Clear();
                        SessionNumber.Clear();
                        Attribute.Clear();
                        indicate = "Attention Span";
                        fillthearray(mednames[o], "Attention_Span");
                    }
                    if (hu == 5)
                    {
                        UsedAmount.Clear();
                        SessionNumber.Clear();
                        Attribute.Clear();
                        indicate = "Score";
                        fillthearray(mednames[o], "Score");
                    }
                    double[] usedamount    = UsedAmount.ToArray();
                    double[] sessionnumber = SessionNumber.ToArray();
                    double[] attributes    = Attribute.ToArray();
                    double[,] doub = new double[sessionnumber.Length, 2];
                    // initiating standardization
                    double sum      = UsedAmount.Sum();
                    double mean     = sum / usedamount.Length;
                    double deletsum = 0;
                    for (int why = 0; why < usedamount.Length; why++)
                    {
                        deletsum += Math.Pow(usedamount[why] - mean, 2);
                    }
                    double variance    = deletsum / usedamount.Length;
                    double stdeviation = Math.Sqrt(variance);
                    //var listarray = new List<double[]>();

                    for (int g = 0; g < usedamount.Length; g++)
                    {
                        doub[g, 0] = 1.0;
                        //if (g == usedamount.Length - 1 && usedamount[g] == usedamount[g - 1])
                        //{
                        //   doub[g, 1] = usedamount[g] + 0.1;
                        //}
                        //else
                        //{
                        doub[g, 1] = (usedamount[g] - mean) / stdeviation;
                        //}
                    }
                    //for(int f=0; f<attributes.Length; f++)
                    //{
                    //  doub[2, f] = attributes[f];
                    //}
                    // {4, 4, 4, 4, 4, 3, 3, 3, 2, 2}
                    //{20, 20, 20, 20, 20, 20, 20, 20, 20, 20}
                    //{1, 2, 3, 4, 5, 6 ,7 ,8 ,9 , 10 }
                    double[] x = { 4, 4, 4, 4, 4, 3, 3, 3, 2, 2 };
                    var      A = DenseMatrix.OfArray(doub);

                    var b  = new DenseVector(attributes);
                    var h  = A.QR().Solve(b);
                    var q  = h[0];
                    var q2 = h[1];



                    maboi[indicate] = Math.Round(q2, 2);
                }
                datatab.Rows.Add(maboi);
                AllEnds.Clear();
                EndNumber.Clear();
                UsedAmounts.Clear();
            }

            mother.Close();
            Linear_Stat_Grid.Columns[0].Width = 75;
        }
        private void btnGetFuncAlongSection_Click(object sender, EventArgs e)
        {
            foreach (SectionDescription sectionDescription in sectionsList)
            {
                PointD p1 = sectionDescription.p1;
                PointD p2 = sectionDescription.p2;
                bool   fromMarginToMargin = false;

                SectionDescription currSection = new SectionDescription(p1, p2, true);

                LineDescription2D l1 = currSection.SectionLine;

                DenseMatrix dmValues         = (DenseMatrix)currImgData.DmSourceData.Clone();
                DenseMatrix dmDistanceToLine = (DenseMatrix)currImgData.DmSourceData.Clone();
                dmDistanceToLine.MapIndexedInplace((row, col, dVal) =>
                {
                    PointD currPt = new PointD(col, row);

                    double dist = currPt.DistanceToLine(l1);
                    return(dist);
                });

                List <Tuple <PointD, double> > dataArray = new List <Tuple <PointD, double> >();
                for (int row = 0; row < dmValues.RowCount; row++)
                {
                    for (int col = 0; col < dmValues.ColumnCount; col++)
                    {
                        if (dmDistanceToLine[row, col] <= sectionGapWidth)
                        {
                            dataArray.Add(new Tuple <PointD, double>(new PointD(col, row), dmValues[row, col]));
                        }
                    }
                }

                List <Tuple <double, double> > dataArrayRotated = dataArray.ConvertAll((tpl) =>
                {
                    Vector2D pointVector = l1.p0.ToVector2D(tpl.Item1);
                    double projection    = pointVector * l1.directionVector;
                    return(new Tuple <double, double>(projection, tpl.Item2));
                });


                double arrayMinPosition = dataArrayRotated.Min <Tuple <double, double> >(tpl1 => tpl1.Item1);
                double arrayMaxPosition = dataArrayRotated.Max <Tuple <double, double> >(tpl1 => tpl1.Item1);
                if (!fromMarginToMargin)
                {
                    Vector2D pointVector      = l1.p0.ToVector2D(p2);
                    double   projection       = pointVector * l1.directionVector;
                    double   p2DoublePosition = projection;

                    arrayMinPosition = Math.Min(0.0d, p2DoublePosition);
                    arrayMaxPosition = Math.Max(0.0d, p2DoublePosition);
                    dataArrayRotated.RemoveAll(tpl => ((tpl.Item1 < arrayMinPosition) || (tpl.Item1 > arrayMaxPosition)));
                }

                dataArrayRotated =
                    dataArrayRotated.ConvertAll <Tuple <double, double> >(
                        tpl => new Tuple <double, double>(tpl.Item1 - arrayMinPosition, tpl.Item2));

                dataArrayRotated.Sort((tpl1, tpl2) => tpl1.Item1.CompareTo(tpl2.Item1));

                FunctionRepresentationForm form1 = new FunctionRepresentationForm();
                form1.dvScatterXSpace     = DenseVector.OfEnumerable(dataArrayRotated.ConvertAll <double>(tpl => tpl.Item1));
                form1.dvScatterFuncValues =
                    DenseVector.OfEnumerable(dataArrayRotated.ConvertAll <double>(tpl => tpl.Item2));

                if ((rtbMinValuesLimit.Text != "") && (rtbMaxValuesLimit.Text != ""))
                {
                    form1.ForcedFuncMinValue = Convert.ToDouble(rtbMinValuesLimit.Text.Replace(".", ","));
                    form1.ForcedFuncMaxValue = Convert.ToDouble(rtbMaxValuesLimit.Text.Replace(".", ","));
                    form1.ForceFuncLimits    = true;
                }


                if (rbtnShowByDots.Checked)
                {
                    form1.scatterFuncDrawingVariant = SequencesDrawingVariants.circles;
                }
                else if (rbtnShowByLine.Checked)
                {
                    form1.scatterFuncDrawingVariant = SequencesDrawingVariants.polyline;
                }

                form1.Show();
                form1.Represent();
            }
        }
Example #40
0
        public Matrix <double> CreateMatrix()
        {
            double val = E / ((1 + nu) * (1 - 2 * nu));

            double d11 = val * (1 - nu);
            double d44 = val * (1 - 2 * nu) / 2;
            double d55 = d44;
            double d12 = val * nu;
            double d22 = d11;
            double d23 = d12;
            double d33 = d11;
            double d13 = d12;
            double d66 = d44;

            Matrix <double> Ke = DenseMatrix.OfArray(new double[, ]
            {
                { lx *ly *lz *((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 6, (ly * (d13 + d55)) / 6, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, (ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 6, (ly * (d13 - d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, (ly * (d13 + d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 12, -(ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, -(ly * (d13 + d55)) / 6, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 12, -(ly * (d13 + d55)) / 12, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, -(ly * (d13 - d55)) / 12 },
                { (lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), (lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), -(lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6 },
                { (ly * (d12 + d55)) / 6, (lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), -(ly * (d12 - d55)) / 6, (lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 12, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), (ly * (d12 + d55)) / 12, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 6, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), -(ly * (d12 + d55)) / 6, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 12, -(lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), (ly * (d12 - d55)) / 12, -(lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))) },
                { lx *ly *lz *(d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, -(ly * (d13 - d55)) / 6, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 6, -(ly * (d13 + d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, -(ly * (d13 + d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 6, -(ly * (d13 - d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, (ly * (d13 + d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 12, (ly * (d13 - d55)) / 6, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, (ly * (d13 - d55)) / 12, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 12, (ly * (d13 + d55)) / 12 },
                { (lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), (lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), -(lx * (d23 + d66)) / 12 },
                { (ly * (d12 - d55)) / 6, (lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 6, (lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), -(ly * (d12 + d55)) / 12, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 12, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), (ly * (d12 + d55)) / 6, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 6, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), -(ly * (d12 - d55)) / 12, -(lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 12, -(lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))) },
                { -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 6, -(ly * (d13 - d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, -(ly * (d13 + d55)) / 12, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 6, -(ly * (d13 + d55)) / 6, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, -(ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 12, (ly * (d13 + d55)) / 12, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, (ly * (d13 - d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 12, (ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, (ly * (d13 + d55)) / 6 },
                { -(lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), -(lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), (lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 12 },
                { (ly * (d12 - d55)) / 12, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), -(ly * (d12 + d55)) / 12, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 6, -(lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), (ly * (d12 - d55)) / 6, -(lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 12, (lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), -(ly * (d12 - d55)) / 12, (lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 6, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), (ly * (d12 + d55)) / 6, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))) },
                { lx *ly *lz *(d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, (ly * (d13 + d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 6, (ly * (d13 - d55)) / 12, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, (ly * (d13 - d55)) / 6, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 6, (ly * (d13 + d55)) / 6, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, -(ly * (d13 - d55)) / 12, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 12, -(ly * (d13 + d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, -(ly * (d13 + d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 12, -(ly * (d13 - d55)) / 6 },
                { -(lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), -(lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), (lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), (lx * (d23 - d66)) / 6 },
                { (ly * (d12 + d55)) / 12, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 12, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), -(ly * (d12 - d55)) / 6, -(lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 6, -(lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), (ly * (d12 - d55)) / 12, (lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 12, (lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), -(ly * (d12 + d55)) / 6, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 6, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))) },
                { lx *ly *lz *(d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 12, (ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, (ly * (d13 + d55)) / 6, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 12, (ly * (d13 + d55)) / 12, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, (ly * (d13 - d55)) / 12, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 6, -(ly * (d13 + d55)) / 6, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, -(ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 6, -(ly * (d13 - d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, -(ly * (d13 + d55)) / 12 },
                { (lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), (lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), -(lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6 },
                { -(ly * (d12 - d55)) / 6, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), (ly * (d12 + d55)) / 6, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 12, (lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), -(ly * (d12 - d55)) / 12, (lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 6, -(lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), (ly * (d12 - d55)) / 6, -(lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 12, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), -(ly * (d12 + d55)) / 12, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))) },
                { -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, -(ly * (d13 + d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 12, -(ly * (d13 - d55)) / 6, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, -(ly * (d13 - d55)) / 12, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 12, -(ly * (d13 + d55)) / 12, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, (ly * (d13 - d55)) / 6, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 6, (ly * (d13 + d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, (ly * (d13 + d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 6, (ly * (d13 - d55)) / 12 },
                { (lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), (lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), -(lx * (d23 - d66)) / 12 },
                { -(ly * (d12 + d55)) / 6, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 6, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), (ly * (d12 - d55)) / 12, (lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 12, (lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), -(ly * (d12 - d55)) / 6, -(lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 6, -(lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), (ly * (d12 + d55)) / 12, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 12, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))) },
                { -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 12, -(ly * (d13 + d55)) / 12, -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, -(ly * (d13 - d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 12, -(ly * (d13 - d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, -(ly * (d13 + d55)) / 6, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), -(lz * (d12 + d44)) / 6, (ly * (d13 - d55)) / 12, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, (ly * (d13 + d55)) / 12, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), (lz * (d12 + d44)) / 6, (ly * (d13 + d55)) / 6, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, (ly * (d13 - d55)) / 6 },
                { -(lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), -(lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), (lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), (lx * (d23 + d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 12 },
                { -(ly * (d12 + d55)) / 12, -(lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), (ly * (d12 - d55)) / 12, -(lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 6, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), -(ly * (d12 + d55)) / 6, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 12, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), (ly * (d12 + d55)) / 12, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 6, (lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))), -(ly * (d12 - d55)) / 6, (lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))) },
                { -lx * ly * lz * (d44 / (9 * (ly * ly)) - d11 / (18 * (lx * lx)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 12, (ly * (d13 - d55)) / 12, -lx * ly * lz * (d11 / (18 * (lx * lx)) + d44 / (18 * (ly * ly)) + d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 12, (ly * (d13 + d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) - d44 / (18 * (ly * ly)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 12, (ly * (d13 + d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 12, (ly * (d13 - d55)) / 6, lx * ly * lz * (d11 / (9 * (lx * lx)) - (2 * d44) / (9 * (ly * ly)) + d55 / (9 * (lz * lz))), (lz * (d12 - d44)) / 6, -(ly * (d13 + d55)) / 12, -lx * ly * lz * (d11 / (9 * (lx * lx)) + d44 / (9 * (ly * ly)) - d55 / (18 * (lz * lz))), (lz * (d12 + d44)) / 6, -(ly * (d13 - d55)) / 12, lx * ly * lz * (d44 / (9 * (ly * ly)) - (2 * d11) / (9 * (lx * lx)) + d55 / (9 * (lz * lz))), -(lz * (d12 - d44)) / 6, -(ly * (d13 - d55)) / 6, lx * ly * lz * ((2 * d11) / (9 * (lx * lx)) + (2 * d44) / (9 * (ly * ly)) + (2 * d55) / (9 * (lz * lz))), -(lz * (d12 + d44)) / 6, -(ly * (d13 + d55)) / 6 },
                { -(lz * (d12 - d44)) / 12, -lx * ly * lz * (d22 / (9 * (ly * ly)) - d44 / (18 * (lx * lx)) + d66 / (9 * (lz * lz))), -(lx * (d23 + d66)) / 6, (lz * (d12 + d44)) / 12, -lx * ly * lz * (d44 / (18 * (lx * lx)) + d22 / (18 * (ly * ly)) + d66 / (18 * (lz * lz))), -(lx * (d23 + d66)) / 12, (lz * (d12 - d44)) / 12, -lx * ly * lz * (d44 / (9 * (lx * lx)) - d22 / (18 * (ly * ly)) + d66 / (9 * (lz * lz))), -(lx * (d23 - d66)) / 12, -(lz * (d12 + d44)) / 12, lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - (2 * d66) / (9 * (lz * lz))), -(lx * (d23 - d66)) / 6, -(lz * (d12 - d44)) / 6, lx * ly * lz * (d44 / (9 * (lx * lx)) - (2 * d22) / (9 * (ly * ly)) + d66 / (9 * (lz * lz))), (lx * (d23 - d66)) / 6, (lz * (d12 + d44)) / 6, -lx * ly * lz * (d44 / (9 * (lx * lx)) + d22 / (9 * (ly * ly)) - d66 / (18 * (lz * lz))), (lx * (d23 - d66)) / 12, (lz * (d12 - d44)) / 6, lx * ly * lz * (d22 / (9 * (ly * ly)) - (2 * d44) / (9 * (lx * lx)) + d66 / (9 * (lz * lz))), (lx * (d23 + d66)) / 12, -(lz * (d12 + d44)) / 6, lx * ly * lz * ((2 * d44) / (9 * (lx * lx)) + (2 * d22) / (9 * (ly * ly)) + (2 * d66) / (9 * (lz * lz))), (lx * (d23 + d66)) / 6 },
                { -(ly * (d12 - d55)) / 12, -(lx * (d23 + d66)) / 6, -lx * ly * lz * (d66 / (9 * (ly * ly)) - d55 / (18 * (lx * lx)) + d33 / (9 * (lz * lz))), (ly * (d12 + d55)) / 12, -(lx * (d23 + d66)) / 12, -lx * ly * lz * (d55 / (18 * (lx * lx)) + d66 / (18 * (ly * ly)) + d33 / (18 * (lz * lz))), (ly * (d12 + d55)) / 6, (lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) - d66 / (18 * (ly * ly)) + d33 / (9 * (lz * lz))), -(ly * (d12 - d55)) / 6, (lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - (2 * d33) / (9 * (lz * lz))), -(ly * (d12 + d55)) / 12, -(lx * (d23 - d66)) / 6, lx * ly * lz * (d55 / (9 * (lx * lx)) - (2 * d66) / (9 * (ly * ly)) + d33 / (9 * (lz * lz))), (ly * (d12 - d55)) / 12, -(lx * (d23 - d66)) / 12, -lx * ly * lz * (d55 / (9 * (lx * lx)) + d66 / (9 * (ly * ly)) - d33 / (18 * (lz * lz))), (ly * (d12 - d55)) / 6, (lx * (d23 + d66)) / 12, lx * ly * lz * (d66 / (9 * (ly * ly)) - (2 * d55) / (9 * (lx * lx)) + d33 / (9 * (lz * lz))), -(ly * (d12 + d55)) / 6, (lx * (d23 + d66)) / 6, lx * ly * lz * ((2 * d55) / (9 * (lx * lx)) + (2 * d66) / (9 * (ly * ly)) + (2 * d33) / (9 * (lz * lz))) },
            });

            return(Ke);

            /*
             *
             * for (int i = 0; i < Ke.RowCount; i++)
             * {
             *  for (int j = 0; j < Ke.ColumnCount; j++)
             *  {
             *      Console.Write(Ke[i, j]);
             *      Console.Write("| ");
             *  }
             *  Console.WriteLine();
             * }
             * Console.WriteLine();
             *
             *
             * Console.ReadKey();
             *
             */
        }
Example #41
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="timeGrid">Time discretisation used.</param>
 /// <param name="factors">Number of factors in the model.</param>
 /// <param name="weights">Precomputed swaption weights.</param>
 /// <param name="correlation">A homogeneous forward correlation matrix.</param>
 public InterestRateVolatilities(PedersenTimeGrid timeGrid, int factors, SwaptionWeights weights, DenseMatrix correlation)
 {
     _volFixed    = false;
     _timeGrid    = timeGrid;
     _factors     = factors;
     _weights     = weights;
     _correlation = correlation;
     _volatility  = new Matrix[_timeGrid.MaxExpiry];
     for (int i = 0; i < _timeGrid.MaxExpiry; i++)
     {
         _volatility[i] = new Matrix(_timeGrid.MaxTenor, _factors);
     }
     _storedImpliedVol     = new double[_timeGrid.MaxExpiry][];
     _storedImpliedVolSq   = new double[_timeGrid.MaxExpiry][];
     _storedImpliedVolTerm = new double[_timeGrid.MaxExpiry][][];
     for (int i = 0; i < _timeGrid.MaxExpiry; i++)
     {
         _storedImpliedVol[i]     = new double[_timeGrid.MaxTenor - i];
         _storedImpliedVolSq[i]   = new double[_timeGrid.MaxTenor - i];
         _storedImpliedVolTerm[i] = new double[_timeGrid.MaxTenor - i][];
         for (int j = 0; j < _timeGrid.MaxTenor - i; j++)
         {
             _storedImpliedVolTerm[i][j] = new double[i + 1];
         }
     }
 }
Example #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserEvd"/> class. This object will compute the
        /// the eigenvalue decomposition when the constructor is called and cache it's decomposition.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="symmetricity">If it is known whether the matrix is symmetric or not the routine can skip checking it itself.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If EVD algorithm failed to converge with matrix <paramref name="matrix"/>.</exception>
        public static UserEvd Create(Matrix <Complex32> matrix, Symmetricity symmetricity)
        {
            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare);
            }

            var order = matrix.RowCount;

            // Initialize matricies for eigenvalues and eigenvectors
            var eigenVectors  = DenseMatrix.CreateIdentity(order);
            var blockDiagonal = Matrix <Complex32> .Build.SameAs(matrix, order, order);

            var eigenValues = new LinearAlgebra.Complex.DenseVector(order);

            bool isSymmetric;

            switch (symmetricity)
            {
            case Symmetricity.Hermitian:
                isSymmetric = true;
                break;

            case Symmetricity.Asymmetric:
                isSymmetric = false;
                break;

            default:
                isSymmetric = matrix.IsHermitian();
                break;
            }

            if (isSymmetric)
            {
                var matrixCopy = matrix.ToArray();
                var tau        = new Complex32[order];
                var d          = new float[order];
                var e          = new float[order];

                SymmetricTridiagonalize(matrixCopy, d, e, tau, order);
                SymmetricDiagonalize(eigenVectors, d, e, order);
                SymmetricUntridiagonalize(eigenVectors, matrixCopy, tau, order);

                for (var i = 0; i < order; i++)
                {
                    eigenValues[i] = new Complex(d[i], e[i]);
                }
            }
            else
            {
                var matrixH = matrix.ToArray();
                NonsymmetricReduceToHessenberg(eigenVectors, matrixH, order);
                NonsymmetricReduceHessenberToRealSchur(eigenVectors, eigenValues, matrixH, order);
            }

            for (var i = 0; i < eigenValues.Count; i++)
            {
                blockDiagonal.At(i, i, (Complex32)eigenValues[i]);
            }

            return(new UserEvd(eigenVectors, eigenValues, blockDiagonal, isSymmetric));
        }
Example #43
0
        /// <summary>
        /// Returns a row of a matrix in a set
        /// </summary>
        /// <param name="matrix">Source matrix</param>
        /// <param name="row">index of the row</param>
        public static Set Row2Set(DenseMatrix matrix, int row)
        {
            var r = matrix.Row(row);

            return(new Set(r.ToArray()));
        }
Example #44
0
        /// <summary>
        /// Returns a column of a matrix in a set
        /// </summary>
        /// <param name="matrix">Source Matrix</param>
        /// <param name="column">index of the column</param>
        ///
        public static Set Column2Set(DenseMatrix matrix, int column)
        {
            var c = matrix.Column(column);

            return(new Set(c.ToArray()));
        }
 public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order)
 {
     Assert.That(() => DenseMatrix.CreateIdentity(order), Throws.TypeOf <ArgumentOutOfRangeException>());
 }
        public void CholeskyFailsWithNonSquareMatrix(int row, int col)
        {
            var I = new DenseMatrix(row, col);

            I.Cholesky();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Convolution2DProcessor{TPixel}"/> class.
 /// </summary>
 /// <param name="kernelX">The horizontal gradient operator.</param>
 /// <param name="kernelY">The vertical gradient operator.</param>
 public Convolution2DProcessor(DenseMatrix <float> kernelX, DenseMatrix <float> kernelY)
 {
     Guard.IsTrue(kernelX.Size.Equals(kernelY.Size), $"{nameof(kernelX)} {nameof(kernelY)}", "Kernel sizes must be the same.");
     this.KernelX = kernelX;
     this.KernelY = kernelY;
 }
 public Matrix3DHomogeneous()
 {
     this.Matrix = DenseMatrix.CreateIdentity(4);
 }
 public ISquareMatrix Id()
 {
     return(new SquareMatrix(DenseMatrix.CreateIdentity(this.RowCount)));
 }
        /// <summary>
        /// Run example
        /// </summary>
        public void Run()
        {
            // Format matrix output to console
            var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();

            formatProvider.TextInfo.ListSeparator = " ";

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            var matrixA = new DenseMatrix(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });

            Console.WriteLine(@"Matrix 'A' with coefficients");
            Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create vector "b" with the constant terms.
            var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });

            Console.WriteLine(@"Vector 'b' with the constant terms");
            Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 1. Solve linear equations using LU decomposition
            var resultX = matrixA.LU().Solve(vectorB);

            Console.WriteLine(@"1. Solution using LU decomposition");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 2. Solve linear equations using QR decomposition
            resultX = matrixA.QR().Solve(vectorB);
            Console.WriteLine(@"2. Solution using QR decomposition");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 3. Solve linear equations using SVD decomposition
            matrixA.Svd(true).Solve(vectorB, resultX);
            Console.WriteLine(@"3. Solution using SVD decomposition");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 4. Solve linear equations using Gram-Shmidt decomposition
            matrixA.GramSchmidt().Solve(vectorB, resultX);
            Console.WriteLine(@"4. Solution using Gram-Shmidt decomposition");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 5. Verify result. Multiply coefficient matrix "A" by result vector "x"
            var reconstructVecorB = matrixA * resultX;

            Console.WriteLine(@"5. Multiply coefficient matrix 'A' by result vector 'x'");
            Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // To use Cholesky or Eigenvalue decomposition coefficient matrix must be
            // symmetric (for Evd and Cholesky) and positive definite (for Cholesky)
            // Multipy matrix "A" by its transpose - the result will be symmetric and positive definite matrix
            var newMatrixA = matrixA.TransposeAndMultiply(matrixA);

            Console.WriteLine(@"Symmetric positive definite matrix");
            Console.WriteLine(newMatrixA.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 6. Solve linear equations using Cholesky decomposition
            newMatrixA.Cholesky().Solve(vectorB, resultX);
            Console.WriteLine(@"6. Solution using Cholesky decomposition");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 7. Solve linear equations using eigen value decomposition
            newMatrixA.Evd().Solve(vectorB, resultX);
            Console.WriteLine(@"7. Solution using eigen value decomposition");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 8. Verify result. Multiply new coefficient matrix "A" by result vector "x"
            reconstructVecorB = newMatrixA * resultX;
            Console.WriteLine(@"8. Multiply new coefficient matrix 'A' by result vector 'x'");
            Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();
        }
        /// <summary>
        /// Run example
        /// </summary>
        public void Run()
        {
            // Format matrix output to console
            var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone();

            formatProvider.TextInfo.ListSeparator = " ";

            // Solve next system of linear equations (Ax=b):
            // 5*x + 2*y - 4*z = -7
            // 3*x - 7*y + 6*z = 38
            // 4*x + 1*y + 5*z = 43

            // Create matrix "A" with coefficients
            var matrixA = DenseMatrix.OfArray(new[, ] {
                { 5.00, 2.00, -4.00 }, { 3.00, -7.00, 6.00 }, { 4.00, 1.00, 5.00 }
            });

            Console.WriteLine(@"Matrix 'A' with coefficients");
            Console.WriteLine(matrixA.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create vector "b" with the constant terms.
            var vectorB = new DenseVector(new[] { -7.0, 38.0, 43.0 });

            Console.WriteLine(@"Vector 'b' with the constant terms");
            Console.WriteLine(vectorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // Create stop criteriums to monitor an iterative calculation. There are next available stop criteriums:
            // - DivergenceStopCriterium: monitors an iterative calculation for signs of divergence;
            // - FailureStopCriterium: monitors residuals for NaN's;
            // - IterationCountStopCriterium: monitors the numbers of iteration steps;
            // - ResidualStopCriterium: monitors residuals if calculation is considered converged;

            // Stop calculation if 1000 iterations reached during calculation
            var iterationCountStopCriterium = new IterationCountStopCriterium <double>(1000);

            // Stop calculation if residuals are below 1E-10 --> the calculation is considered converged
            var residualStopCriterium = new ResidualStopCriterium(1e-10);

            // Create monitor with defined stop criteriums
            var monitor = new Iterator(new IIterationStopCriterium <double>[] { iterationCountStopCriterium, residualStopCriterium });

            // Create Generalized Product Bi-Conjugate Gradient solver
            var solver = new GpBiCg(monitor);

            // 1. Solve the matrix equation
            var resultX = solver.Solve(matrixA, vectorB);

            Console.WriteLine(@"1. Solve the matrix equation");
            Console.WriteLine();

            // 2. Check solver status of the iterations.
            // Solver has property IterationResult which contains the status of the iteration once the calculation is finished.
            // Possible values are:
            // - CalculationCancelled: calculation was cancelled by the user;
            // - CalculationConverged: calculation has converged to the desired convergence levels;
            // - CalculationDiverged: calculation diverged;
            // - CalculationFailure: calculation has failed for some reason;
            // - CalculationIndetermined: calculation is indetermined, not started or stopped;
            // - CalculationRunning: calculation is running and no results are yet known;
            // - CalculationStoppedWithoutConvergence: calculation has been stopped due to reaching the stopping limits, but that convergence was not achieved;
            Console.WriteLine(@"2. Solver status of the iterations");
            Console.WriteLine(solver.IterationResult);
            Console.WriteLine();

            // 3. Solution result vector of the matrix equation
            Console.WriteLine(@"3. Solution result vector of the matrix equation");
            Console.WriteLine(resultX.ToString("#0.00\t", formatProvider));
            Console.WriteLine();

            // 4. Verify result. Multiply coefficient matrix "A" by result vector "x"
            var reconstructVecorB = matrixA * resultX;

            Console.WriteLine(@"4. Multiply coefficient matrix 'A' by result vector 'x'");
            Console.WriteLine(reconstructVecorB.ToString("#0.00\t", formatProvider));
            Console.WriteLine();
        }
Example #52
0
        /*
         * function [BH,mean_dist]=sc_compute(Bsamp,Tsamp,mean_dist,nbins_theta,nbins_r,r_inner,r_outer,out_vec);
         * % [BH,mean_dist]=sc_compute(Bsamp,Tsamp,mean_dist,nbins_theta,nbins_r,r_inner,r_outer,out_vec);
         * %
         * % compute (r,theta) histograms for points along boundary
         * %
         * % Bsamp is 2 x nsamp (x and y coords.)
         * % Bsamp是2n长的数组,提供x,y
         * % Tsamp is 1 x nsamp (tangent theta)
         * % Tsamp是n长的数组,提供tan(theta)
         * % out_vec is 1 x nsamp (0 for inlier, 1 for outlier)
         * % out_vec是n长的数组,表示是否野点
         * %
         * % mean_dist is the mean distance, used for length normalization
         * % mean_dist是平均距离,用来归一化
         * % if it is not supplied, then it is computed from the data
         * %
         * % outliers are not counted in the histograms, but they do get
         * % assigned a histogram
         * %
         * end
         */
        public Matrix ComputeSC(Matrix Bsamp, Matrix Tsamp, double?mean_dist, out double mean_dist_out, bool[] out_vec)
        {
            //nsamp=size(Bsamp,2);
            //% 求n长
            //int nsamp = Bsamp.Columns;

            //in_vec=out_vec==0;
            //% 初始化野点标记数组吧?
            var in_vec = Utils.InitArray <bool>(nsamp, true);

            out_vec.FillArray(false);

            //% compute r,theta arrays 计算r和t的数组
            //r_array=real(sqrt(dist2(Bsamp',Bsamp'))); % real is needed to
            //                                          % prevent bug in Unix version
            //% r_array是Bsamp的转置和Bsamp的转置之间的dist2
            //% 应该是个n*n的数组了
            var Bsampt  = Bsamp.Transpose();
            var r_array = Dist2(Bsampt, Bsampt).Each(Math.Sqrt);

            //theta_array_abs=atan2(Bsamp(2,:)'*ones(1,nsamp)-ones(nsamp,1)*Bsamp(2,:),Bsamp(1,:)'*ones(1,nsamp)-ones(nsamp,1)*Bsamp(1,:))';
            var theta_array_abs = new DenseMatrix(nsamp, nsamp);
            var x_array         = Bsamp.GetRow(0);
            var y_array         = Bsamp.GetRow(1);

            for (int i = 0; i < nsamp; ++i)
            {
                for (int j = 0; j < nsamp; ++j)
                {
                    double xi = x_array[i], yi = y_array[i],
                           xj = x_array[j], yj = y_array[j];
                    theta_array_abs[j, i] = Math.Atan2(yi - yj, xi - xj);
                }
            }

            var Tsampt = Tsamp.Transpose();

            //theta_array=theta_array_abs-Tsamp'*ones(1,nsamp);
            //% 不知道这里是干什么,但是theta_array应该是theta的二维数组
            var theta_array = theta_array_abs - Tsampt * Ones(1, nsamp);

            //% create joint (r,theta) histogram by binning r_array and
            //% theta_array
            //% 通过对r_array和theta_array插槽来求直方图

            //% normalize distance by mean, ignoring outliers
            //% 通过均值来归一化距离参数,忽略野点
            //if isempty(mean_dist)
            if (mean_dist == null)
            {
                //   tmp=r_array(in_vec,:);
                //   tmp=tmp(:,in_vec);
                //   mean_dist=mean(tmp(:));
                //end
                double mean_sum   = 0;
                int    mean_count = 0;
                for (int i = 0; i < r_array.Rows; ++i)
                {
                    for (int j = 0; j < r_array.Columns; ++j)
                    {
                        if (in_vec[i] && in_vec[j])
                        {
                            mean_sum += r_array[i, j];
                            ++mean_count;
                        }
                    }
                }
                mean_dist_out = mean_sum / mean_count;
            }
            else
            {
                mean_dist_out = mean_dist.Value;
            }
            //% 看不懂,但是应该是求非野点的平均值吧,结果存在mean_dist中
            //r_array_n=r_array/mean_dist;
            //% r_array_n是规范化结果,用均值规范化,而不是用最大值,难道我错了?
            var r_array_n = r_array / mean_dist_out;

            //% use a log. scale for binning the distances
            //r_bin_edges=logspace(log10(r_inner),log10(r_outer),5);
            var r_bin_edges = Utils.LogSpace(Math.Log10(r_inner), Math.Log10(r_outer), nbins_r);

            //r_array_q=zeros(nsamp,nsamp);
            var r_array_q = Zeros(nsamp, nsamp);

            //for m=1:nbins_r %m从1循环到r槽数
            for (int i = 0; i < nbins_r; ++i)
            {
                //   r_array_q=r_array_q+(r_array_n<r_bin_edges(m)); % r_array_q = r_array_q + (r_array_n < r_bin_edges(m))
                r_array_q = r_array_q + r_array_n.Each(v => v < r_bin_edges[i] ? 1 : 0);
                //   % 这个代码的意思应该是说r_array_q中下标小于m的项统统加上r_array_n中小于r_bin_edges(m)的项目数
                //end
            }
            //fz=r_array_q>0; % flag all points inside outer boundary
            //% fz为r_array_q中大于0的项目标记(这应该是个数组)
            var fz = r_array_q.Each(v => v > 0 ? 1 : 0);

            //% put all angles in [0,2pi) range
            //theta_array_2 = rem(rem(theta_array,2*pi)+2*pi,2*pi);
            //% 将所有方向角都弄到[0,2pi)范围内,看不懂
            //% 猜测theta_array_2 = theta_array.Select(t => (t % (2*pi) + (2*pi)) % (2*pi))
            var theta_array_2 = theta_array.Each(t => (t % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI));

            //% quantize to a fixed set of angles (bin edges lie on 0,(2*pi)/k,...2*pi
            //% 将方向角量化到固定的角度
            //theta_array_q = 1+floor(theta_array_2/(2*pi/nbins_theta));
            //% theta_array_q = theta_array_2.Select(t => floor(t / (2*pi/nbins_theta)) + 1)
            //% 这是以1为起点的吧
            var theta_array_q = theta_array_2.Each(t => (int)(t / (2 * Math.PI / nbins_theta)));

            //nbins=nbins_theta*nbins_r;
            int nbins = nbins_theta * nbins_r;
            //% 不用说
            //BH=zeros(nsamp,nbins);

            var BH = Zeros(nsamp, nbins);

            //% BH应该就是最后的直方图
            //for n=1:nsamp % n从1循环到nsamp
            for (int i = 0; i < nsamp; ++i)
            {
                //   fzn=fz(n,:)&in_vec;
                //   Sn=sparse(theta_array_q(n,fzn), r_array_q(n,fzn), 1, nbins_theta, nbins_r);
                //   % sparse这里貌似是生成稀疏矩阵的,Sn应该是用于计算匹配代价的直方图,而BH是包含野点的
                //   BH(n,:)=Sn(:)'; % 转置
                for (int j = 0; j < nsamp; ++j)
                {
                    int tq = (int)theta_array_q[i, j], tr = (int)r_array_q[i, j];
                    if (tr > 0)
                    {
                        tr--;
                        ++BH[i, tr *nbins_theta + tq];
                    }
                }
            }

            return(BH);
        }
Example #53
0
        public static RBFNetSolution SolveOLS(List <Vec> xs, List <double> ys, double tolerance, double spread, Func <bool> cancelled = null)
        {
            Func <Vec, Vec, double> phi = (x, c) => Phi(x, c, spread);
            var maxCenters = (int)Math.Min(xs.Count, Math.Max(1, 4 * Math.Sqrt(xs.Count)));
            var centers    = new List <Vec>(xs);
            var n          = xs.Count;
            var m          = centers.Count;

            Mat P = new DenseMatrix(n, m);

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    P[i, j] = phi(xs[i], centers[j]);
                }
            }

            Vec dOrig = new DenseVector(ys.ToArray());
            Vec d     = dOrig.Subtract(dOrig.Average());
            Vec dNorm = d.Normalize(2);

            var    candidateBases = centers.Zip(P.Columns(), (ci, pi) => new { Center = ci, Basis = pi }).ToList();
            var    selectedBases  = candidateBases.Select(cb => new { Center = cb.Center, Basis = cb.Basis, OrthoBasis = cb.Basis }).Take(0).ToList();
            double qualityTotal   = 0;

            var context = QMCreateOrthoContext(n, m);
            var iters   = m;

            for (int k = 0; k < iters; k++)
            {
                int      stride = n;
                double[] selectedOrthonormalBases = new double[selectedBases.Count * stride];
                for (int ptr = 0, sb = 0; sb < selectedBases.Count; ptr += stride, sb++)
                {
                    Array.Copy(selectedBases[sb].OrthoBasis.ToArray(), 0, selectedOrthonormalBases, ptr, stride);
                }

                var best = candidateBases.Select(cb => {
                    var pi = cb.Basis;
                    Vec w;
                    if (!selectedBases.Any())
                    {
                        w = pi.Normalize(2);
                    }
                    else
                    {
                        double[] result = new double[pi.Count];
                        double[] pis    = pi.ToList().ToArray();
                        double[] sobs   = selectedOrthonormalBases.ToList().ToArray();
                        QMOrthogonalize(context, pis, selectedBases.Count, sobs);
                        w = new DenseVector(pis.ToList().ToArray());
                    }
                    //Vec wCheck = Orthogonalize(pi, selectedBases.Select(b => b.OrthoBasis).ToList()).Normalize(2);
                    //var w = wCheck;
                    //Debug.Assert(w.Subtract(wCheck).Norm(2) < 0.0001);
                    var err = Math.Pow(w.DotProduct(dNorm), 2);
                    return(new { Center = cb.Center, OrthoBasis = w, Quality = err, Candidate = cb });
                }).OrderByDescending(q => q.Quality).First();
                candidateBases.Remove(best.Candidate);
                selectedBases.Add(new { Center = best.Center, Basis = best.Candidate.Basis, OrthoBasis = best.OrthoBasis });
                qualityTotal += best.Quality;
                if (1 - qualityTotal < tolerance || (cancelled != null && cancelled()))
                {
                    break;
                }
            }
            QMDestroyOrthoContext(context);

            //Trace.WriteLine(string.Format("Centers: {0}, Spread: {1}, Tolerance: {2}", selectedBases.Count, spread, tolerance));

            var weights = SolveLS(
                new Vec[] { DenseVector.Create(n, _ => 1) }.Concat(selectedBases.Select(sb => sb.Basis)).ColumnsToMatrix(),
                new DenseVector(ys.ToArray()));
            bool isDegenerate = false;

            if (weights.Any(w => double.IsNaN(w)))
            {
                Trace.WriteLine("! Degenerate RBF network !");
                isDegenerate = true;
            }
            var allBases = selectedBases.ToList();

            allBases.Insert(0, null);
            var resultBases = allBases.Zip(weights, (b, w) => new RadialBasis(b != null ? b.Center : null, w)).ToList();

            return(new RBFNetSolution(resultBases, spread, isDegenerate));
        }
        public void CholeskyFailsWithNonSquareMatrix()
        {
            var matrix = new DenseMatrix(3, 1);

            Assert.Throws <ArgumentException>(() => matrix.Cholesky());
        }
Example #55
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            double xi;                         //, x0, xs;

            xi = ((Value.Number)args[1]).Item; // Number
            xi = Math.Round(xi);
            if (xi < Double.Epsilon)
            {
                throw new Exception("The point count must be larger than 0.");
            }

            //x0 = ((Value.Number)args[2]).Item;// Starting Coord
            //xs = ((Value.Number)args[3]).Item;// Spacing


            var result = FSharpList <Value> .Empty;

            Curve crvRef = null;

            if (((Value.Container)args[0]).Item is CurveElement)
            {
                var c = (CurveElement)((Value.Container)args[0]).Item; // Curve
                crvRef = c.GeometryCurve;
            }
            else
            {
                crvRef = (Curve)((Value.Container)args[0]).Item; // Curve
            }

            double t = 0.0;

            XYZ startPoint = !dynXYZOnCurveOrEdge.curveIsReallyUnbound(crvRef) ? crvRef.Evaluate(t, true) : crvRef.Evaluate(t * crvRef.Period, false);

            result = FSharpList <Value> .Cons(Value.NewContainer(startPoint), result);

            pts.Add(startPoint);

            t = 1.0;
            XYZ endPoint = !dynXYZOnCurveOrEdge.curveIsReallyUnbound(crvRef) ? crvRef.Evaluate(t, true) : crvRef.Evaluate(t * crvRef.Period, false);

            if (xi > 2.0 + Double.Epsilon)
            {
                int numParams = Convert.ToInt32(xi - 2.0);

                var curveParams = new List <double>();

                for (int ii = 0; ii < numParams; ii++)
                {
                    curveParams.Add((ii + 1.0) / (xi - 1.0));
                }

                int maxIterNum = 15;

                int iterNum = 0;
                for (; iterNum < maxIterNum; iterNum++)
                {
                    XYZ prevPoint = startPoint;
                    XYZ thisXYZ   = null;
                    XYZ nextXYZ   = null;

                    Vector <double> distValues = DenseVector.Create(numParams, (c) => 0.0);

                    Matrix <double> iterMat    = DenseMatrix.Create(numParams, numParams, (r, c) => 0.0);
                    double          maxDistVal = -1.0;
                    for (int iParam = 0; iParam < numParams; iParam++)
                    {
                        t = curveParams[iParam];

                        if (nextXYZ != null)
                        {
                            thisXYZ = nextXYZ;
                        }
                        else
                        {
                            thisXYZ = !dynXYZOnCurveOrEdge.curveIsReallyUnbound(crvRef) ? crvRef.Evaluate(t, true) : crvRef.Evaluate(t * crvRef.Period, false);
                        }

                        double tNext = (iParam == numParams - 1) ?  1.0 : curveParams[iParam + 1];
                        nextXYZ = (iParam == numParams - 1) ? endPoint :
                                  !dynXYZOnCurveOrEdge.curveIsReallyUnbound(crvRef) ? crvRef.Evaluate(tNext, true) : crvRef.Evaluate(tNext * crvRef.Period, false);

                        distValues[iParam] = thisXYZ.DistanceTo(prevPoint) - thisXYZ.DistanceTo(nextXYZ);

                        if (Math.Abs(distValues[iParam]) > maxDistVal)
                        {
                            maxDistVal = Math.Abs(distValues[iParam]);
                        }
                        Transform thisDerivTrf = !dynXYZOnCurveOrEdge.curveIsReallyUnbound(crvRef) ? crvRef.ComputeDerivatives(t, true) : crvRef.ComputeDerivatives(t * crvRef.Period, false);
                        XYZ       derivThis    = thisDerivTrf.BasisX;
                        double    distPrev     = thisXYZ.DistanceTo(prevPoint);
                        if (distPrev > Double.Epsilon)
                        {
                            double valDeriv = (thisXYZ - prevPoint).DotProduct(derivThis) / distPrev;
                            iterMat[iParam, iParam] += valDeriv;
                            if (iParam > 0)
                            {
                                iterMat[iParam - 1, iParam] -= valDeriv;
                            }
                        }
                        double distNext = thisXYZ.DistanceTo(nextXYZ);
                        if (distNext > Double.Epsilon)
                        {
                            double valDeriv = (thisXYZ - nextXYZ).DotProduct(derivThis) / distNext;

                            iterMat[iParam, iParam] -= valDeriv;
                            if (iParam < numParams - 1)
                            {
                                iterMat[iParam + 1, iParam] += valDeriv;
                            }
                        }
                        prevPoint = thisXYZ;
                    }

                    Matrix <double> iterMatInvert = iterMat.Inverse();
                    Vector <double> changeValues  = iterMatInvert.Multiply(distValues);

                    for (int iParam = 0; iParam < numParams; iParam++)
                    {
                        curveParams[iParam] -= changeValues[iParam];

                        if (iParam == 0 && curveParams[iParam] < 0.000000001)
                        {
                            curveParams[iParam] = 0.5 * (changeValues[iParam] + curveParams[iParam]);
                        }
                        else if (iParam > 0 && curveParams[iParam] < 0.000000001 + curveParams[iParam - 1])
                        {
                            curveParams[iParam] = 0.5 * (curveParams[iParam - 1] + changeValues[iParam] + curveParams[iParam]);
                        }
                        else if (iParam == numParams - 1 && curveParams[iParam] > 1.0 - 0.000000001)
                        {
                            curveParams[iParam] = 0.5 * (1.0 + changeValues[iParam] + curveParams[iParam]);
                        }
                    }
                    if (maxDistVal < 0.000000001)
                    {
                        for (int iParam = 0; iParam < numParams; iParam++)
                        {
                            t       = curveParams[iParam];
                            thisXYZ = !dynXYZOnCurveOrEdge.curveIsReallyUnbound(crvRef) ? crvRef.Evaluate(t, true) : crvRef.Evaluate(t * crvRef.Period, false);
                            result  = FSharpList <Value> .Cons(Value.NewContainer(thisXYZ), result);

                            pts.Add(thisXYZ);
                        }
                        break;
                    }
                }

                if (iterNum == maxIterNum)
                {
                    throw new Exception("could not solve for equal distances");
                }
            }

            if (xi > 1.0 + Double.Epsilon)
            {
                result = FSharpList <Value> .Cons(Value.NewContainer(endPoint), result);

                pts.Add(endPoint);
            }
            return(Value.NewList(
                       ListModule.Reverse(result)
                       ));
        }
        /// <summary>
        /// Формирует bitmap, отображающий линейку для представления ее визуально на форме.
        /// </summary>
        /// <param name="dimX">The x dimension to form the ruler bitmap</param>
        /// <param name="dimY">The y dimension to form the ruler bitmap</param>
        /// <param name="withMarker">if set to <c>true</c> then there will be little triangle marker displayed at the marker position.</param>
        /// <returns></returns>
        public Bitmap RulerBitmap(int dimX, int dimY, bool withMarker = true)
        {
            currentDimX = dimX;
            currentDimY = dimY;
            DenseMatrix dmRulerDenseMatrix = null;


            //if (!colorScheme.isSchemeGrayscaled)
            //{
            //Bitmap scaleBM = new Bitmap(currentDimX, currentDimY);
            //int nodesCount = colorScheme.colorsArray.Count;


            //Image<Bgr, byte> scaleImage = new Image<Bgr, byte>(scaleBM);
            //dmRulerDenseMatrix = ImageProcessing.DenseMatrixFromImage(scaleBM);

            dmRulerDenseMatrix = DenseMatrix.Create(currentDimY, currentDimX, new Func <int, int, double>
                                                    (
                                                        (y, x) =>
            {
                double curValue = (double)y;
                curValue        = 1.0d - (1.0d + curValue) / (double)currentDimY;
                curValue        = minValue + curValue * (maxValue - minValue);
                return(curValue);
            }
                                                    ));

            //for (int i = 0; i < dmRulerDenseMatrix.RowCount; i++)
            //{
            //    double curValue = (double)i;
            //    curValue = 1.0d - (1.0d + curValue) / (double)currentDimY;
            //    curValue = minValue + curValue * (maxValue - minValue);
            //    DenseVector tmpDenseVector = DenseVector.Create(dmRulerDenseMatrix.ColumnCount, i1 => curValue);
            //    dmRulerDenseMatrix.SetRow(i, tmpDenseVector);
            //}
            Image <Bgr, double> scaleImage = ImageProcessing.evalResultColored(dmRulerDenseMatrix, null, colorScheme).Convert <Bgr, double>();


            if (withMarker)
            {
                double  yPositionDouble = (1.0d - ((markerPositionValue - minValue) / (maxValue - minValue))) * (double)currentDimY;
                int     yPosition       = Convert.ToInt32(Math.Round(yPositionDouble));
                Point[] polyLine        = new Point[] { new Point(currentDimX - 10, yPosition), new Point(currentDimX, yPosition - 5), new Point(currentDimX, yPosition + 5) };
                Bgr     markerColor     = ImageProcessing.ContrastColorFromBgrColor(colorScheme.GetColorByValueAndRange(markerPositionValue, minValue, maxValue));
                scaleImage.DrawPolyline(polyLine, true, markerColor, 1);
                scaleImage.FillConvexPoly(polyLine, markerColor);
            }


            if (selection != null)
            {
                Image <Bgr, double> tmpHighlightingImage = scaleImage.CopyBlank();
                tmpHighlightingImage.Draw(RectangleOnImageFromRealValuesRectangle((RectangleF)(selection.SelectionRectReal), scaleImage), new Bgr(255, 255, 255), -1);
                scaleImage = scaleImage.AddWeighted(tmpHighlightingImage, 0.8, 0.3, 0.0);
                scaleImage.Draw(RectangleOnImageFromRealValuesRectangle((RectangleF)(selection.SelectionRectReal), scaleImage), new Bgr(255, 255, 255), 1);
            }

            if (HighlightMaskRelative != null)
            {
                scaleImage = scaleImage.Mul(ImageProcessing.ConvertGrayImageToBgr(HighlightMaskRelative));
            }


            #region Прописываем текстовые маркеры

            MCvFont theFont = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_PLAIN, 1.0d, 1.0d);
            theFont.thickness = 2;
            double dMarkersCount = (double)currentDimY / 30.0d;
            dMarkersCount = (dMarkersCount > 10.0d) ? (10.0d) : (dMarkersCount);
            //int markersCount = Convert.ToInt32(Math.Truncate(dMarkersCount));
            double dRulerValueGap = (maxValue - minValue) / (double)dMarkersCount;
            dRulerValueGap = (dRulerValueGap < 1.0d) ? (1.0d) : dRulerValueGap;
            int    deciGap          = Convert.ToInt32(Math.Truncate(Math.Log(dRulerValueGap, 2.0d)));
            double rulerValueGap    = Math.Pow(2.0, (double)deciGap);
            double lowerMarkerValue = minValue - Math.IEEERemainder(minValue, rulerValueGap);
            lowerMarkerValue = (lowerMarkerValue < minValue) ? (lowerMarkerValue + rulerValueGap) : (lowerMarkerValue);
            double currentMarkerValue = lowerMarkerValue;
            while (currentMarkerValue < maxValue)
            {
                double        yPositionDouble = (1.0d - ((currentMarkerValue - minValue) / (maxValue - minValue))) * (double)currentDimY;
                int           yPosition       = Convert.ToInt32(Math.Round(yPositionDouble));
                LineSegment2D theLine         = new LineSegment2D(new Point(0, yPosition), new Point(5, yPosition));
                //Point[] polyLine = new Point[] { new Point(currentDimX - 10, yPosition), new Point(currentDimX, yPosition - 5), new Point(currentDimX, yPosition + 5) };
                Bgr markerColor = ImageProcessing.ContrastColorFromBgrColor(colorScheme.GetColorByValueAndRange(currentMarkerValue, minValue, maxValue));
                scaleImage.Draw(theLine, markerColor, 2);
                String message = Math.Round(currentMarkerValue, 2).ToString();



                scaleImage.Draw(message, ref theFont, new Point(5, yPosition), markerColor);
                // scaleImage.Draw(message, new Point(5, yPosition), Emgu.CV.CvEnum.FontFace.HersheyPlain, 1.0d, markerColor);

                currentMarkerValue += rulerValueGap;
            }
            #endregion Прописываем текстовые маркеры

            Bitmap scaleBM = new Bitmap(scaleImage.Bitmap);

            return(scaleBM);

            #region // obsolete
            //}
            //else
            //{
            //    Bitmap scaleBM = new Bitmap(currentDimX, dimY);
            //    Image<Bgr, byte> scaleImage = new Image<Bgr, byte>(scaleBM);
            //    for (int i = 1; i <= dimY; i++)
            //    {
            //        int yLow = dimY - i;
            //        Rectangle curRect = new Rectangle(0, yLow, currentDimX, 1);
            //        scaleImage.Draw(curRect, colorScheme.GetColorByValueAndRange(((double)i / (double)dimY) * (maxValue - minValue), minValue, maxValue), 0);
            //    }
            //
            //    if (withMarker)
            //    {
            //        double yPositionDouble = (1.0d - (markerPositionValue / (maxValue - minValue))) * (double)dimY;
            //        int yPosition = Convert.ToInt32(Math.Round(yPositionDouble));
            //        Point[] polyLine = new Point[] { new Point(currentDimX - 10, yPosition), new Point(currentDimX, yPosition - 5), new Point(currentDimX, yPosition + 5) };
            //        Bgr markerColor = ImageProcessing.ContrastColorFromBgrColor(colorScheme.GetColorByValueAndRange(markerPositionValue, minValue, maxValue));
            //        scaleImage.DrawPolyline(polyLine, true, markerColor, 1);
            //        scaleImage.FillConvexPoly(polyLine, markerColor);
            //    }
            //
            //
            //    if (selection != null)
            //    {
            //        Image<Bgr, byte> tmpHighlightingImage = scaleImage.CopyBlank();
            //        tmpHighlightingImage.Draw(RectangleOnImageFromRealValuesRectangle((RectangleF)(selection.SelectionRectReal), scaleBM), new Bgr(255, 255, 255), -1);
            //        scaleImage = scaleImage.AddWeighted(tmpHighlightingImage, 1.0, 0.3, 0.0);
            //        scaleImage.Draw(RectangleOnImageFromRealValuesRectangle((RectangleF)(selection.SelectionRectReal), scaleBM), new Bgr(255, 255, 255), 1);
            //    }
            //
            //
            //    scaleBM = new Bitmap(scaleImage.Bitmap);
            //
            //    return scaleBM;
            //}
            #endregion // obsolete
        }
Example #57
0
        public void LUFailsWithNonSquareMatrix()
        {
            var matrix = new DenseMatrix(3, 2);

            Assert.Throws <ArgumentException>(() => matrix.LU());
        }
Example #58
0
 /// <summary>
 /// Returns the transpose of a matrix.
 /// </summary>
 /// <param name="matrix">a matrix</param>
 public static DenseMatrix Transpose(DenseMatrix matrix)
 {
     return(DenseMatrix.OfMatrix(matrix.Transpose()));
 }
Example #59
0
        public static DenseMatrix SVDGetTransMat(DenseMatrix mat_source, DenseMatrix mat_target, ref CellIndex cellIndex, out double ErrValue)
        {
            //4 * NSamples
            int CellsCount = 8;


            DenseMatrix matP = mat_source.SubMatrix(0, 3, 0, mat_source.ColumnCount) as DenseMatrix;

            if (cellIndex == null)
            {
                DenseMatrix matQ_init = mat_target.SubMatrix(0, 3, 0, mat_target.ColumnCount) as DenseMatrix;
                cellIndex = CellIndex.GetCellIndex(matQ_init, CellsCount);
            }

            DenseMatrix matQ = cellIndex.DoPointMatch(matP);

            DenseMatrix matErr = matQ - matP;

            ErrValue = 0;
            for (int i = 0; i < matErr.ColumnCount; i++)
            {
                ErrValue += Math.Sqrt(matErr[0, i] * matErr[0, i] + matErr[1, i] * matErr[1, i] + matErr[2, i] * matErr[2, i]);
            }


            DenseMatrix matP_Mean = Utils_PCA.getMeanMat(matP);
            DenseMatrix matQ_Mean = Utils_PCA.getMeanMat(matQ);

            DenseMatrix matT_MoveP = DenseMatrix.CreateIdentity(4);
            DenseMatrix matT_MoveQ = DenseMatrix.CreateIdentity(4);

            for (int i = 0; i < 3; i++)
            {
                matT_MoveP[i, 3] = matP_Mean[i, 0];
                matT_MoveQ[i, 3] = matQ_Mean[i, 0];
            }


            matP = matP - matP_Mean;
            matQ = matQ - matQ_Mean;


            DenseMatrix matM = matP * matQ.Transpose() as DenseMatrix;

            //matM.SplitUV(matU, matV, 0.01);
            MathNet.Numerics.LinearAlgebra.Factorization.Svd <double> svd = matM.Svd(true);

            DenseMatrix matU  = svd.U as DenseMatrix;
            DenseMatrix matVT = svd.VT as DenseMatrix;


            DenseMatrix matR = (matU * matVT).Transpose() as DenseMatrix;
            DenseMatrix matT = DenseMatrix.CreateIdentity(4);

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    matT[i, j] = matR[i, j];
                }
            }

            matT = matT_MoveP.Inverse() * matT * matT_MoveQ as DenseMatrix;

            return(matT);
        }
Example #60
0
 async Task <Matrix <double> > BuildMatrix(Func <int, int, double> formula)
 {
     return(DenseMatrix.Create(n, n, formula));
 }